Ejemplo n.º 1
0
 bool sorty(const P& a, const P& b) {//y軸を優先
   return imag(a) != imag(b) ? imag(a) < imag(b) : real(a) < real(b);
 }
Ejemplo n.º 2
0
/// Dummy functions for library instantations
int dummy_cl(complex<long> z) {
  int a;
  a = real(z) + imag(z);
  return (a);
}
Ejemplo n.º 3
0
void tvector<nr_type_t>::print (void) {
  for (int r = 0; r < size; r++) {
    fprintf (stderr, "%+.2e%+.2ei\n", (double) real (get (r)),
	     (double) imag (get (r)));
  }
}
Ejemplo n.º 4
0
void
eval_nroots(void)
{
	volatile int h, i, k, n;

	push(cadr(p1));
	eval();

	push(caddr(p1));
	eval();
	p2 = pop();
	if (p2 == symbol(NIL))
		guess();
	else
		push(p2);

	p2 = pop();
	p1 = pop();

	if (!ispoly(p1, p2))
		stop("nroots: polynomial?");

	// mark the stack

	h = tos;

	// get the coefficients

	push(p1);
	push(p2);
	n = coeff();
	if (n > YMAX)
		stop("nroots: degree?");

	// convert the coefficients to real and imaginary doubles

	for (i = 0; i < n; i++) {
		push(stack[h + i]);
		real();
		yyfloat();
		eval();
		p1 = pop();
		push(stack[h + i]);
		imag();
		yyfloat();
		eval();
		p2 = pop();
		if (!isdouble(p1) || !isdouble(p2))
			stop("nroots: coefficients?");
		c[i].r = p1->u.d;
		c[i].i = p2->u.d;
	}

	// pop the coefficients

	tos = h;

	// n is the number of coefficients, n = deg(p) + 1

	monic(n);

	for (k = n; k > 1; k--) {
		findroot(k);
		if (fabs(a.r) < DELTA)
			a.r = 0.0;
		if (fabs(a.i) < DELTA)
			a.i = 0.0;
		push_double(a.r);
		push_double(a.i);
		push(imaginaryunit);
		multiply();
		add();
		divpoly(k);
	}

	// now make n equal to the number of roots

	n = tos - h;

	if (n > 1) {
		sort_stack(n);
		p1 = alloc_tensor(n);
		p1->u.tensor->ndim = 1;
		p1->u.tensor->dim[0] = n;
		for (i = 0; i < n; i++)
			p1->u.tensor->elem[i] = stack[h + i];
		tos = h;
		push(p1);
	}
}
Ejemplo n.º 5
0
void LCGWSpinBBHNR1::Computehpc(double t)
{
	double hpl, hcr;
	double AmpT;
	dcomplex Yp;
	dcomplex Yn;
	dcomplex img(0.0, 1.0);
	dcomplex h, dhdtau;
	
	hpl = 0.0;
	hcr = 0.0;
	
#ifdef _DEBUG_GW_  
    if((DEBUGDispAll)&&(t>1000.)){
        DispAllParam(MT->o);
        DEBUGDispAll=false;
    }
#endif
    

	
	if ((t>tStartWave)&&(t<=tEndWave)){
		
		
		for(int iH=2; iH<lmax+1; iH++){
			for(int jH=1; jH<iH+1; jH++){
				Yp = SpherHarm(iH, jH);
				Yn = SpherHarm(iH, -jH);
                
                if((OutputType==1)||(OutputType==2))
                    dhdtau = (dhpharmdtau(iH, jH, t) - img * dhcharmdtau(iH, jH, t))*Yp + (dhpharmdtau(iH, -jH, t) - img * dhcharmdtau(iH, -jH, t))*Yn;
                
                if((OutputType==0)||(OutputType==2))
                    h = (hpharm(iH, jH, t) - img * hcharm(iH, jH, t))*Yp + (hpharm(iH, -jH, t) - img * hcharm(iH, -jH, t))*Yn;
                
                //if((t>1000.)&&(t<1100.))
                //    Cout << t << " " << t/M << " "  << OutputType << " " << iH << " " << jH << " " << real(h) << " " << imag(h) << " " << real(dhdtau) << " " << imag(dhdtau) << Endl; 
                
                
                
                if(OutputType==1){
                    h = dhdtau/M;
                }
                
                if(OutputType==2){
                    h = h/M - dhdtau*(t-tShiftHybObs)/(M*M);
                    h *= LC::TSUN;
                }
                    
                //if((OutputType==2)&&(t>100.)&&(jH==2))
                //    Cout << " " << real(h) << " " << imag(h) << Endl; 
                
				hpl += real(h);
				hcr += -imag(h);

				//Cout << iH << " " << jH << " : " << h << " " << hpharm(iH, jH, t) << " " << hcharm(iH, jH, t) << " " << hpl << " " << hcr << " " << hpharm(iH, -jH, t) << " " << hcharm(iH, -jH, t)  << Endl;
			} 
			
		}
		
		/*	
		 if(lmax < 3){
		 Yp = SpherHarm(2, 2);
		 Yn = SpherHarm(2, -2);
		 h = (hpharm(2, 2, t) - img * hcharm(2, 2, t))*Yp + (hpharm(2, -2, t) - img * hcharm(2, -2, t))*Yn;
		 hpl += real(h);
		 hcr += -imag(h);
		 
		 Yp = SpherHarm(2, 1);
		 Yn = SpherHarm(2, -1);
		 h = (hpharm(2, 1, t) - img * hcharm(2, 1, t))*Yp + (hpharm(2, -1, t) - img * hcharm(2, -1, t))*Yn;
		 hpl += real(h);
		 hcr += -imag(h);
		 }
		 
		 
		 if(lmax < 4){
		 Yp = SpherHarm(3, 3);
		 Yn = SpherHarm(3, -3);
		 h = (hpharm(3, 3, t) - img * hcharm(3, 3, t))*Yp + (hpharm(3, -3, t) - img * hcharm(3, -3, t))*Yn;
		 hpl += real(h);
		 hcr += -imag(h);
		 }
		 
		 
		 if(lmax < 5){
		 Yp = SpherHarm(4, 4);
		 Yn = SpherHarm(4, -4);
		 h = (hpharm(4, 4, t) - img * hcharm(4, 4, t))*Yp + (hpharm(4, -4, t) - img * hcharm(4, -4, t))*Yn;
		 hpl += real(h);
		 hcr += -imag(h);
		 }
		 
		 
		 if(lmax < 6){
		 Yp = SpherHarm(5, 5);
		 Yn = SpherHarm(5, -5);
		 h = (hpharm(5, 5, t) - img * hcharm(5, 5, t))*Yp + (hpharm(5, -5, t) - img * hcharm(5, -5, t))*Yn;
		 hpl += real(h);
		 hcr += -imag(h);
		 }
		 
		 
		 if(lmax < 7){
		 Yp = SpherHarm(6, 6);
		 Yn = SpherHarm(6, -6);
		 h = (hpharm(6, 6, t) - img * hcharm(6, 6, t))*Yp + (hpharm(6, -6, t) - img * hcharm(6, -6, t))*Yn;
		 hpl += real(h);
		 hcr += -imag(h);
		 }
		 
		 
		 if(lmax < 8){
		 Yp = SpherHarm(7, 7);
		 Yn = SpherHarm(7, -7);
		 h = (hpharm(7, 7, t) - img * hcharm(7, 7, t))*Yp + (hpharm(7, -7, t) - img * hcharm(7, -7, t))*Yn;
		 hpl += real(h);
		 hcr += -imag(h);
		 }
		 
		 */
		
		//!  h+ and hx in SSB are compute in LCGW::ComputehBpc(double t) of LISACODE-GW.cpp
		
		//hBpLast = - Amp * (hpl * c2psi + hcr * s2psi);   // Are they defined before ?
		//hBcLast = - Amp * (-hpl * s2psi + hcr * c2psi);  // Are they defined before ?
		
		if(ApplyTaper)
			AmpT = Amp*GWSBHHH->halfhann(t, tendTaper, tTaper);
		else
			AmpT = Amp;
		
	//	hBpLast = - AmpT * hpl;
	//	hBcLast = - AmpT * hcr;

        
        hBpLast = - Amp * (hpl * c2psi + hcr * s2psi);   // Are they defined before ?
		hBcLast = - Amp * (-hpl * s2psi + hcr * c2psi);  // Are they defined before ?
		
#ifdef _DEBUG_GW_     
        (*DEBUGfCheck) << " " << hpl << " " << hcr << " " << hBpLast << " " << hBcLast  ;
#endif
        
		
	}else{
		hBpLast = 0.0;
		hBcLast = 0.0;
	}
    
	
}
Ejemplo n.º 6
0
Archivo: ovm_mpq.c Proyecto: pcpa/owl
void
ovm_q_pow(oregister_t *l, oregister_t *r)
{
    switch (r->t) {
	case t_void:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = 1.0;
	    }
	    else {
		l->t = t_mpr;
		mpfr_set_ui(orr(l), 1, thr_rnd);
	    }
	    break;
	case t_word:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = pow(mpq_get_d(oqr(l)), r->v.w);
	    }
	    else {
		mpfr_set_si(orr(r), r->v.w, thr_rnd);
		goto mpr;
	    }
	    break;
	case t_float:
	    if (mpq_sgn(oqr(l)) < 0 &&
		finite(r->v.d) && rint(r->v.d) != r->v.d) {
		real(r->v.dd) = r->v.d;
		imag(r->v.dd) = 0.0;
		goto cdd;
	    }
	    l->t = t_float;
	    l->v.d = pow(mpq_get_d(oqr(l)), r->v.d);
	    break;
	case t_mpz:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = pow(mpq_get_d(oqr(l)), mpz_get_d(ozr(r)));
	    }
	    else {
		mpfr_set_z(orr(r), ozr(r), thr_rnd);
		goto mpr;
	    }
	    break;
	case t_rat:
	    if (mpq_sgn(oqr(l)) < 0) {
		if (!cfg_float_format) {
		    real(r->v.dd) = mpq_get_d(oqr(r));
		    imag(r->v.dd) = 0.0;
		    goto cdd;
		}
		mpc_set_q(occ(r), oqr(r), thr_rndc);
		goto mpc;
	    }
	    else {
		if (!cfg_float_format) {
		    l->t = t_float;
		    l->v.d = pow(mpq_get_d(oqr(l)), rat_get_d(r->v.r));
		}
		else {
		    mpq_set_si(oqr(r), rat_num(r->v.r), rat_den(r->v.r));
		    mpfr_set_q(orr(r), oqr(r), thr_rnd);
		    goto mpr;
		}
	    }
	    break;
	case t_mpq:
	    if (mpq_sgn(oqr(r)) < 0) {
		if (!cfg_float_format) {
		    real(r->v.dd) = mpq_get_d(oqr(r));
		    imag(r->v.dd) = 0.0;
		    goto cdd;
		}
		mpc_set_q(occ(r), oqr(r), thr_rndc);
		goto mpc;
	    }
	    else {
		if (!cfg_float_format) {
		    l->t = t_float;
		    l->v.d = pow(mpq_get_d(oqr(l)), mpq_get_d(oqr(r)));
		}
		else {
		    mpfr_set_q(orr(r), oqr(r), thr_rnd);
		    goto mpr;
		}
	    }
	    break;
	case t_mpr:
	    if (mpq_sgn(oqr(l)) < 0 &&
		mpfr_number_p(orr(r)) && !mpfr_integer_p(orr(r))) {
		mpc_set_q(occ(r), oqr(r), thr_rndc);
		goto mpc;
	    }
	mpr:
	    l->t = t_mpr;
	    mpfr_set_q(orr(l), oqr(l), thr_rnd);
	    mpfr_pow(orr(l), orr(l), orr(r), thr_rnd);
	    break;
	case t_cdd:
	cdd:
	    l->t = t_cdd;
	    real(l->v.dd) = mpq_get_d(oqr(l));
	    imag(l->v.dd) = 0.0;
	    l->v.dd = cpow(l->v.dd, r->v.dd);
	    check_cdd(l);
	    break;
	case t_cqq:
	    if (!cfg_float_format) {
		real(r->v.dd) = mpq_get_d(oqr(r));
		imag(r->v.dd) = mpq_get_d(oqi(r));
		goto cdd;
	    }
	    mpc_set_q_q(occ(r), oqr(r), oqi(r), thr_rndc);
	case t_mpc:
	mpc:
	    l->t = t_mpc;
	    mpc_set_q(occ(l), oqr(l), thr_rndc);
	    mpc_pow(occ(l), occ(l), occ(r), thr_rndc);
	    check_mpc(l);
	    break;
	default:
	    ovm_raise(except_not_a_number);
    }
}
Ejemplo n.º 7
0
void
test()
{
    std::complex<T> z(1.5, 2.5);
    assert(imag(z) == 2.5);
}
Ejemplo n.º 8
0
int main() {

    double hbarc = 197.327; // hbar * c in [MeV fm]
    double Mass = 938; // nucleon mass in MeV

    std::string input_dir = "Input/";

    // Read Nucleus File
    std::string nucleus_string;
    std::ifstream nucleus_file( "domgen.config" );

    nucleus_file >> nucleus_string;

    nucleus_file.close();
    nucleus_file.clear();

    // Read Configuration file
    std::string config_filename = nucleus_string + ".config";
    std::ifstream config_file( config_filename.c_str() );

    std::string parameters_string;
    int fit_ph;
    double rmax;
    int rpts;
    int lmax;
    config_file >> parameters_string >> fit_ph;
    config_file >> rmax >> rpts >> lmax;

    int num_lj;
    config_file >> num_lj;
    // Knowing the expected number of bound states is useful when
    // looking for particle states that are near the continuum

    // These maps hold the number of bound states for each lj
    std::map<std::string, int> n_lj_map; // neutrons
    std::map<std::string, int> p_lj_map; // protons
    std::vector< std::map< std::string, int > > map_vec;
    for ( int n = 0; n < num_lj; ++n ) {

        std::string key;
        int n_num_bound, p_num_bound;
        config_file >> key >> n_num_bound >> p_num_bound;

        std::pair< std::map< std::string, int >::iterator, bool > n_ret;
        std::pair< std::map< std::string, int >::iterator, bool > p_ret;
        n_ret = n_lj_map.insert ( std::make_pair( key, n_num_bound ) );
        p_ret = p_lj_map.insert ( std::make_pair( key, p_num_bound ) );

        if ( n_ret.second == false ) {
            
            std::cout << "element " << key << " already exists "; 
            std::cout << "with a value of " << n_ret.first->second << std::endl;
        }

        if ( p_ret.second == false ) {
            
            std::cout << "element " << key << " already exists "; 
            std::cout << "with a value of " << p_ret.first->second << std::endl;
        }
    }

    map_vec.push_back( n_lj_map );
    map_vec.push_back( p_lj_map );



    config_file.close();
    config_file.clear();

  //  std::string output_dir = "Output_" + parameters_string + "/Ener/";
  //  std::string parameters_filename = parameters_string + ".inp";

    std::string output_dir = "Output_test/S/";
   // std::string parameters_filename = "Output_hosfit/roott/Nov26/hosfitupdated.inp";
    std::string parameters_filename = "Input.inp";

    std::cout << "rmax = " << rmax << std::endl;
    std::cout << "rpts = " << rpts << std::endl;
    std::cout << "lmax = " << lmax << std::endl;

    std::string n_string = "n" + nucleus_string;
    std::string p_string = "p" + nucleus_string;

    std::string n_filename = input_dir + n_string + ".inp";
    std::string p_filename = input_dir + p_string + ".inp";

    // Create Nuclear Parameter Objects
    NuclearParameters Nu_n = read_nucleus_parameters( n_filename );
    NuclearParameters Nu_p = read_nucleus_parameters( p_filename );

    std::vector< NuclearParameters > Nu_vec;
    Nu_vec.push_back( Nu_n );
    Nu_vec.push_back( Nu_p );


    // Read in DOM parameters
    std::ifstream pfile( parameters_filename.c_str() );
    if ( pfile.is_open() !=1 ) {
        std::cout << "could not open file " << parameters_filename << std::endl;
        std::abort();
    }
    pfile.close();
    pfile.clear();

    std::string L_array[8] = { "s", "p", "d", "f", "g", "h", "i", "j" };
    std::string J_array[8] = { "1", "3", "5", "7", "9", "11", "13", "15" };

    // Create momentum space grid
    std::vector<double> kmesh;
    std::vector<double> kweights;
    double const kmax = 6.0;
    int const kpts = 104;
    kmesh.resize( kpts );
    kweights.resize( kpts );
    GausLeg( 0., kmax, kmesh, kweights );

    // Create radial grid
    std::vector<double> rmesh;
    std::vector<double> rweights;
    double rdelt = rmax / rpts;
    for( int i = 0; i < rpts; ++i ) {

        rmesh.push_back( ( i + 0.5 ) * rdelt );
        rweights.push_back( rdelt );
    }

    // Prepare stuff for output files
    std::vector< std::string > np_strings;
    np_strings.push_back( n_string );
    np_strings.push_back( p_string );

    double total_energy = 0;
    double calc_A = 0;

    //Potential specifications
    int type = 1; // 1 is P.B. form (average), 0 is V.N. form
    int mvolume = 4;
    int AsyVolume = 1;

    // --- CALCULATIONS --- //

        std::string lj_particleN_share = output_dir + "ParticleN_shares.out";
        std::ofstream particleNumber_file( lj_particleN_share.c_str() );
    // Loop over protons and neutrons
    double Zp; // number of protons in projectile

    for ( unsigned int nu = 0; nu < Nu_vec.size(); ++nu ) {
        
        std::map< std::string, int > lj_map = map_vec[nu];

        double tz = nu - 0.5; // +0.5 for protons, -0.5 for neutrons
        if ( tz < 0 ) {Zp = 0;} else { Zp = 1;}
         particleNumber_file << tz << std::endl;

        // Nucleus Object
        const NuclearParameters &Nu = Nu_vec[nu];

        // Construct Parameters Object
        Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, Zp );

        // Construct Potential Object
        pot U = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p );
        pot *U1 = &U;
       // lmax = 0;
        // Construct boundRspace Object
//      double Emax = Nu.Ef - Nu.Wgap * p.fGap_B; // energy < Ef where imaginary part begins
        double Emax =  Nu.Ef;
        double Emin = -200 + Emax;
        boundRspace B( rmax, rpts, Nu.Ef, Nu.ph_gap, lmax , Nu.Z, Zp, Nu.A, U1 );

        double tol = 0.01;
        std::vector< lj_eigen_t > bound_levels = B.get_bound_levels( rmesh, tol );

        std::vector< mesh_t > emesh_vec = B.get_emeshes( rmesh, Emin, Emax, bound_levels );

        std::vector<double> n_of_k;
        n_of_k.assign( kmesh.size(), 0 );
        std::vector<double> n_of_k_qh;
        n_of_k_qh.assign( kmesh.size(), 0 );
        std::vector<double> n_of_k_c_tot;
        n_of_k_c_tot.assign( kmesh.size(), 0 );
        std::vector<double> n_of_k_qh_peak_tot;
        n_of_k_qh_peak_tot.assign( kmesh.size(), 0 );

        // Loop over lj channels
        for ( int l = 0; l < lmax + 1 ; ++l ) {

            // Create Bessel Function matrix in k and r
            matrix_t bess_mtx( kmesh.size(), rmesh.size() );
            for( unsigned int nk = 0; nk < kmesh.size(); ++nk ) {
            for( unsigned int nr = 0; nr < rmesh.size(); ++nr ) {

                double rho = kmesh[nk] * rmesh[nr];

                bess_mtx( nk, nr ) = gsl_sf_bessel_jl( l, rho );
            }
            }

            for( int up = -1; up < 2; up+=2 ) {

                double xj = l + up / 2.0;
                int j_index = ( up - 1 ) / 2;
                if ( xj < 0 ) continue;

                std::string j_string;
                if ( l == 0 ) j_string = J_array[ l ];
                else j_string = J_array[ l + j_index ];

                int index = B.index_from_LJ( l, xj );
                mesh_t &emesh = emesh_vec[index];
                std::vector< eigen_t > &bound_info = bound_levels[index];

                std::string lj_string = L_array[l] + j_string + "2";

                std::vector<double> n_of_k_c_lj;
                std::vector<double> n_of_k_qh_lj;
                std::vector<double> n_of_k_qh_peak;
                std::vector<std::vector<double> > n_of_k_qh_peak_Matrice;
                n_of_k_c_lj.assign( kmesh.size(), 0 );
                n_of_k_qh_lj.assign( kmesh.size(), 0 );
                n_of_k_qh_peak.assign( kmesh.size(), 0 );

	        matrix_t Slj(kmesh.size(),kmesh.size());
		for (int i=0;i<kmesh.size();++i){for (int j=0;j<kmesh.size();++j){Slj(i,j) = 0.;}}
	        matrix_t n_r_lj(rmesh.size(),rmesh.size());
		for (int i=0;i<rmesh.size();++i){for (int j=0;j<rmesh.size();++j){n_r_lj(i,j) = 0.;}}

                // Find self-consistent solutions
                 std::cout << "lj = " << l << " " << xj << std::endl;
                 std::vector<cmatrix_t> G;  
		 double E;
		 vector<double> Edelt;
                for ( unsigned int m = 0; m < emesh.size(); ++m ) {
                    
                     E = emesh[m].first;
       		     Edelt.push_back(emesh[m].second);
                    // Propagator
	            G.push_back( B.propagator( rmesh, E, l, xj));
	        }
                // Loop over energy
		    for (int i = 0 ; i < rmesh.size(); ++i){
		         for (int j = 0 ; j < rmesh.size(); ++j){
			     double sumnr = 0.;
                             for ( unsigned int m = 0; m < emesh.size(); ++m ) {
			            sumnr += rmesh[i] * rmesh[j] * imag(G[m](i,j)) * Edelt[m];
		            }
		    n_r_lj(i,j) = sumnr;	
		         }
                    }
                  //  for( unsigned int nk = 0; nk < kmesh.size(); ++nk ) {
                    for( unsigned int mk = 0; mk < kmesh.size(); ++mk ) {
                         double rsums = 0;
                        for( unsigned int i = 0; i < rmesh.size(); ++i ) {
                            double jl1 = bess_mtx( mk, i );
                        for( unsigned int j = 0; j < rmesh.size(); ++j ) {
                            double jl2 = bess_mtx( mk, j );
                            
                            rsums -= n_r_lj(i,j) * jl1 * jl2 * rdelt;
                        }
                        } // end loop over radial coordinates
		//	Slj(nk,mk) = 2./M_PI/M_PI * rsums * ( 2 * xj + 1 )/( 4 * M_PI ); 		
			 n_of_k_c_lj[mk] += 2./M_PI/M_PI * rsums * ( 2 * xj + 1 )/( 4 * M_PI ); 		
		    }
                   // }    // integral over k
                     
                      // end loop over k
                 // end loop over energy
//                for (int nk = 0 ; nk < kmesh.size() ; ++nk){
//		     n_of_k_c_lj[nk] = Slj(nk,nk);} 
                // loop over the orbitals and write out the 
                // bound state information to a file
                for ( unsigned int N = 0; N < bound_info.size(); ++N ) {
                    // Quasiparticle energy
                    double QPE = bound_info[N].first; 

                    // Quasiparticle wavefunction
                    std::vector<double> &QPF = bound_info[N].second;

                    // Transform wavefunction to momentum space
                    std::vector<double> kQPF;
                    for( unsigned int nk = 0; nk < kmesh.size(); ++nk ) {

                        double sum = 0;
                        for( unsigned int i = 0; i < rmesh.size(); ++i ) {

                           sum += std::sqrt( 2 / M_PI ) * rweights[i] 
                                * std::pow( rmesh[i], 2 ) * QPF[i] * bess_mtx( nk, i );
                        }
                        kQPF.push_back( sum );
                      }

                    // This should automatically be normalized to N or Z
                    // since the wavefunctions are normalized to 1
                    if ( QPE < Nu.Ef ) {
                        for ( unsigned int kk = 0; kk < kmesh.size(); ++kk ) {

                            n_of_k_qh_lj[kk] += ( 2 * xj + 1 ) / ( 4 * M_PI ) * kQPF[kk] * kQPF[kk]; 
                        } // end loop over k
                    } 
                } // end loop over N 
                // Write Out Momentum Distribution for each lj channel
                // Also, add up the contribution from each channel to get 
                // the total momentum distribution
                std::string n_of_k_lj_filename = output_dir + "n_of_k_" 
                                               + np_strings[nu] 
                                               + "_" + L_array[l] + j_string 
                                               + "2.out";
                std::ofstream n_of_k_lj_file( n_of_k_lj_filename.c_str() );
		double NOFK_lj = 0;
                for ( unsigned int i = 0; i < kmesh.size(); ++i ) {
                    double n_of_k_lj = n_of_k_c_lj[i] + n_of_k_qh_peak[i];

                    n_of_k_lj_file << kmesh[i] << " " << n_of_k_lj 
                                   << " " << n_of_k_qh_lj[i] << std::endl;

                    n_of_k[i] += n_of_k_lj;
                    n_of_k_qh[i] += n_of_k_qh_lj[i];
                    n_of_k_qh_peak_tot[i] += n_of_k_qh_peak[i];
                    n_of_k_c_tot[i] += n_of_k_c_lj[i];

		    //Particle contribution to each state
		    // 
		    NOFK_lj += 4 * M_PI * kweights[i] * std::pow( kmesh[i], 2 ) * n_of_k_lj;
                }

                particleNumber_file <<index <<" " << "l= "<< l << " " <<"j= " << xj <<" " << NOFK_lj   << std::endl; 
				  //  <<" " <<n_of_k_qh_peak_tot[sarekar-1] <<" " <<n_of_k_c_tot[sarekar-1] <<std::endl;

                n_of_k_lj_file.close();
                n_of_k_lj_file.clear();
	    }//up
         }//lj
        // Output Files
        std::string strength_filename = output_dir + np_strings[nu] 
                                      + "_k_strength.out";
        std::ofstream strength_file( strength_filename.c_str() );

        std::string n_of_k_filename = output_dir + np_strings[nu]
                                    + "_momentum_dist.out";
        std::ofstream n_of_k_file( n_of_k_filename.c_str() ); 

        // Calculate Particle Number and Kinetic Energy
        double norm = 0;
        for ( unsigned int n = 0; n < kmesh.size(); ++n ) {
            norm += 4 * M_PI * kweights[n] * std::pow( kmesh[n], 2 ) * n_of_k[n];
        }
        // Energetics
        double N_or_Z; // actual number of neutrons or protons
        if( tz > 0 ) { 
            N_or_Z = Nu.Z;
        }
        else {
            N_or_Z = Nu.N();
        }

        calc_A += norm;
        double k_strength = 0;
        double qh_strength = 0;
        for ( unsigned int n = 0; n < kmesh.size(); ++n ) {
            n_of_k_file << kmesh[n] << " " << n_of_k[n] / norm        
                                    << " " << n_of_k_qh[n] / N_or_Z 
                                    << std::endl;

            //verify that n_of_k_qh is normalized to N or Z
            qh_strength += 4 * M_PI * kweights[n] * std::pow( kmesh[n], 2 ) 
                     * n_of_k_qh[n] / N_or_Z;

            k_strength += 4 * M_PI * kweights[n] * std::pow( kmesh[n], 2 ) 
                        * n_of_k[n] / norm;
            
            strength_file << kmesh[n] << " " << k_strength 
                                      << " " << qh_strength << std::endl;
        }

        strength_file << " " << std::endl;
        strength_file << "norm = " << norm << std::endl;
        strength_file << "N or Z = " << N_or_Z << std::endl;

        n_of_k_file.close();
        n_of_k_file.clear();
        strength_file.close();
        strength_file.clear();

std::cout<< "HELLO tz LOOP" <<std::endl;
    }//tz
particleNumber_file.close();
return 1;
}
Ejemplo n.º 9
0
void CopyTensorPotentialToEpetraMatrix(Epetra_FECrsMatrix_Ptr epetraMatrix, blitz::Array<cplx, Rank> potentialData, list pyLocalBasisPairs, blitz::TinyVector<int, Rank> globalStrides, double cutoff)
{
	blitz::Array<int, 2> indexArray;
	indexArray.resize(4 * potentialData.size(), 2);
	indexArray = -100;

	double sqrCutoff = sqr(cutoff);

	//Setup structures for calculating matrix row/col indices from the 
	//basis pairs in the tensor potential
	blitz::TinyVector< blitz::Array<int, 2>, Rank > localBasisPairs;
	for (int rank=0; rank<Rank; rank++)
	{
		localBasisPairs(rank).reference( boost::python::extract< blitz::Array<int, 2> >(pyLocalBasisPairs[rank]) );
	}

	//Iterate over all items in potentialData
	typename blitz::Array<cplx, Rank>::iterator it = potentialData.begin();
	for (int linearCount=0; linearCount<potentialData.size(); linearCount++)
	{
		int globalRow = 0;
		int globalCol = 0;
		for (int rank=0; rank<Rank; rank++)
		{
			int rankPos = it.position()(rank);
			globalRow += globalStrides(rank) * localBasisPairs(rank)(rankPos, 0);
			globalCol += globalStrides(rank) * localBasisPairs(rank)(rankPos, 1);
		}

		double realVal = real(*it);
		double imagVal = imag(*it);

		//Skip padded elements (they have negative row/col index)
		if ((globalRow < 0) || (globalCol < 0))
		{
			it++;
			continue;
		}
		
		/*
		 * Because epetra does not support complex natively,
		 * each matrix element is a 2x2 block
		 *
		 * (A_r  -A_i )  (c_r)  =  (A_r + i A_i) * (c_r + i c_i)  =  A * c
		 * (A_i   A_r )  (c_i)
		 *
		 * Detect if A_i or A_r is zero to avoid redundant elements
		 */

		//Insert values into matrix
		if (sqr(realVal) > sqrCutoff)
		{
			int r,c;
			r = 2*globalRow; c = 2*globalCol;
			indexArray(4*linearCount, 0) = r;
			indexArray(4*linearCount, 1) = c;
			epetraMatrix->InsertGlobalValues(r, 1, &realVal, &c);
			r++; c++;
			epetraMatrix->InsertGlobalValues(r, 1, &realVal, &c);
			indexArray(4*linearCount+1, 0) = r;
			indexArray(4*linearCount+1, 1) = c;
		}
		if (sqr(imagVal) > sqrCutoff)
		{
			int r,c;
			//Upper row, A_i with minus sign
			r = 2*globalRow; c = 2*globalCol+1;
			indexArray(4*linearCount+2, 0) = r;
			indexArray(4*linearCount+2, 1) = c;
			imagVal = -imagVal;
			epetraMatrix->InsertGlobalValues(r, 1, &imagVal, &c);

			//Lower row, A_i without minus sign
			imagVal = -imagVal;
			epetraMatrix->InsertGlobalValues(c, 1, &imagVal, &r);
			indexArray(4*linearCount+3, 0) = c;
			indexArray(4*linearCount+3, 1) = r;
		}
		++it;	
	}
}
Ejemplo n.º 10
0
void State::calculate_expected_values(void) {
    int ini_halo_x = grid->inner_start_x - grid->start_x;
    int ini_halo_y = grid->inner_start_y - grid->start_y;
    int end_halo_x = grid->end_x - grid->inner_end_x;
    int end_halo_y = grid->end_y - grid->inner_end_y;
    int tile_width = grid->end_x - grid->start_x;


    double x, y;
    double sum_norm2 = 0.;
    double sum_x_mean = 0, sum_xx_mean = 0, sum_y_mean = 0, sum_yy_mean = 0;
    double sum_px_mean = 0, sum_pxpx_mean = 0, sum_py_mean = 0,
           sum_pypy_mean = 0,
           param_px = - 1. / grid->delta_x,
           param_py = 1. / grid->delta_y;
    double sum_angular_momentum = 0;

    complex<double> const_1 = -1. / 12., const_2 = 4. / 3., const_3 = -2.5;
    complex<double> derivate1_1 = 1. / 6., derivate1_2 = - 1., derivate1_3 = 0.5, derivate1_4 = 1. / 3.;

#ifndef HAVE_MPI
    #pragma omp parallel for reduction(+:sum_norm2,sum_x_mean,sum_y_mean,sum_xx_mean,sum_yy_mean,sum_px_mean,sum_py_mean,sum_pxpx_mean,sum_pypy_mean,sum_angular_momentum) private(x,y)
#endif
    for (int i = ini_halo_y; i < grid->inner_end_y - grid->start_y; ++i) {
        complex<double> psi_up, psi_down, psi_center, psi_left, psi_right;
        complex<double> psi_up_up, psi_down_down, psi_left_left, psi_right_right;

        for (int j = ini_halo_x; j < grid->inner_end_x - grid->start_x; ++j) {
            psi_center = complex<double> (p_real[i * tile_width + j], p_imag[i * tile_width + j]);
            map_lattice_to_coordinate_space(grid, j, i, &x, &y);
            complex<double> x_r = x;
            complex<double> y_r = y;

            sum_norm2 += real(conj(psi_center) * psi_center);
            sum_x_mean += real(conj(psi_center) * psi_center * x_r);
            sum_y_mean += real(conj(psi_center) * psi_center * y_r);
            sum_xx_mean += real(conj(psi_center) * psi_center * x_r * x_r);
            sum_yy_mean += real(conj(psi_center) * psi_center * y_r * y_r);

            if (i - (ini_halo_y) >= (ini_halo_y == 0) * 2 &&
                    i < grid->inner_end_y - grid->start_y - (end_halo_y == 0) * 2 &&
                    j - (ini_halo_x) >= (ini_halo_x == 0) * 2 &&
                    j < grid->inner_end_x - grid->start_x - (end_halo_x == 0) * 2) {

                psi_up = complex<double> (p_real[(i - 1) * tile_width + j],
                                          p_imag[(i - 1) * tile_width + j]);
                psi_down = complex<double> (p_real[(i + 1) * tile_width + j],
                                            p_imag[(i + 1) * tile_width + j]);
                psi_right = complex<double> (p_real[i * tile_width + j + 1],
                                             p_imag[i * tile_width + j + 1]);
                psi_left = complex<double> (p_real[i * tile_width + j - 1],
                                            p_imag[i * tile_width + j - 1]);
                psi_up_up = complex<double> (p_real[(i - 2) * tile_width + j],
                                             p_imag[(i - 2) * tile_width + j]);
                psi_down_down = complex<double> (p_real[(i + 2) * tile_width + j],
                                                 p_imag[(i + 2) * tile_width + j]);
                psi_right_right = complex<double> (p_real[i * tile_width + j + 2],
                                                   p_imag[i * tile_width + j + 2]);
                psi_left_left = complex<double> (p_real[i * tile_width + j - 2],
                                                 p_imag[i * tile_width + j - 2]);


                sum_px_mean += imag(conj(psi_center) * (derivate1_4 * psi_right + derivate1_3 * psi_center + derivate1_2 * psi_left + derivate1_1 * psi_left_left));
                sum_py_mean += imag(conj(psi_center) * (derivate1_4 * psi_up + derivate1_3 * psi_center + derivate1_2 * psi_down + derivate1_1 * psi_down_down));
                sum_pxpx_mean += real(conj(psi_center) * (const_1 * psi_right_right + const_2 * psi_right + const_2 * psi_left + const_1 * psi_left_left + const_3 * psi_center));
                sum_pypy_mean += real(conj(psi_center) * (const_1 * psi_down_down + const_2 * psi_down + const_2 * psi_up + const_1 * psi_up_up + const_3 * psi_center));
                sum_angular_momentum += imag(conj(psi_center) * (y_r / grid->delta_x * (derivate1_4 * psi_right + derivate1_3 * psi_center + derivate1_2 * psi_left + derivate1_1 * psi_left_left)
                                             + x_r / grid->delta_y * (derivate1_4 * psi_up + derivate1_3 * psi_center + derivate1_2 * psi_down + derivate1_1 * psi_down_down)));
            }
        }
    }
    norm2 = sum_norm2;
    mean_X = sum_x_mean;
    mean_Y = sum_y_mean;
    mean_XX = sum_xx_mean;
    mean_YY = sum_yy_mean;
    mean_Px = - sum_px_mean * param_px;
    mean_Py = - sum_py_mean * param_py;
    mean_PxPx = - sum_pxpx_mean * param_px * param_px;
    mean_PyPy = - sum_pypy_mean * param_py * param_py;
    mean_angular_momentum = sum_angular_momentum;

#ifdef HAVE_MPI
    double *norm2_mpi = new double[grid->mpi_procs];
    double *mean_X_mpi = new double[grid->mpi_procs];
    double *mean_Y_mpi = new double[grid->mpi_procs];
    double *mean_XX_mpi = new double[grid->mpi_procs];
    double *mean_YY_mpi = new double[grid->mpi_procs];
    double *mean_Px_mpi = new double[grid->mpi_procs];
    double *mean_Py_mpi = new double[grid->mpi_procs];
    double *mean_PxPx_mpi = new double[grid->mpi_procs];
    double *mean_PyPy_mpi = new double[grid->mpi_procs];
    double *mean_angular_momentum_mpi = new double[grid->mpi_procs];

    MPI_Allgather(&norm2, 1, MPI_DOUBLE, norm2_mpi, 1, MPI_DOUBLE, grid->cartcomm);
    MPI_Allgather(&mean_X, 1, MPI_DOUBLE, mean_X_mpi, 1, MPI_DOUBLE, grid->cartcomm);
    MPI_Allgather(&mean_Y, 1, MPI_DOUBLE, mean_Y_mpi, 1, MPI_DOUBLE, grid->cartcomm);
    MPI_Allgather(&mean_XX, 1, MPI_DOUBLE, mean_XX_mpi, 1, MPI_DOUBLE, grid->cartcomm);
    MPI_Allgather(&mean_YY, 1, MPI_DOUBLE, mean_YY_mpi, 1, MPI_DOUBLE, grid->cartcomm);
    MPI_Allgather(&mean_Px, 1, MPI_DOUBLE, mean_Px_mpi, 1, MPI_DOUBLE, grid->cartcomm);
    MPI_Allgather(&mean_Py, 1, MPI_DOUBLE, mean_Py_mpi, 1, MPI_DOUBLE, grid->cartcomm);
    MPI_Allgather(&mean_PxPx, 1, MPI_DOUBLE, mean_PxPx_mpi, 1, MPI_DOUBLE, grid->cartcomm);
    MPI_Allgather(&mean_PyPy, 1, MPI_DOUBLE, mean_PyPy_mpi, 1, MPI_DOUBLE, grid->cartcomm);
    MPI_Allgather(&mean_angular_momentum, 1, MPI_DOUBLE, mean_angular_momentum_mpi, 1, MPI_DOUBLE, grid->cartcomm);

    norm2 = 0.;
    mean_X = 0.;
    mean_Y = 0.;
    mean_XX = 0.;
    mean_YY = 0.;
    mean_Px = 0.;
    mean_Py = 0.;
    mean_PxPx = 0.;
    mean_PyPy = 0.;
    mean_angular_momentum = 0.;

    for(int i = 0; i < grid->mpi_procs; i++) {
        norm2 += norm2_mpi[i];
        mean_X += mean_X_mpi[i];
        mean_Y += mean_Y_mpi[i];
        mean_XX += mean_XX_mpi[i];
        mean_YY += mean_YY_mpi[i];
        mean_Px += mean_Px_mpi[i];
        mean_Py += mean_Py_mpi[i];
        mean_PxPx += mean_PxPx_mpi[i];
        mean_PyPy += mean_PyPy_mpi[i];
        mean_angular_momentum += mean_angular_momentum_mpi[i];
    }
    delete [] norm2_mpi;
    delete [] mean_X_mpi;
    delete [] mean_Y_mpi;
    delete [] mean_XX_mpi;
    delete [] mean_YY_mpi;
    delete [] mean_Px_mpi;
    delete [] mean_Py_mpi;
    delete [] mean_PxPx_mpi;
    delete [] mean_PyPy_mpi;
    delete [] mean_angular_momentum_mpi;
#endif
    mean_X = mean_X / norm2;
    mean_Y = mean_Y / norm2;
    mean_XX = mean_XX / norm2;
    mean_YY = mean_YY / norm2;
    mean_Px = mean_Px / norm2;
    mean_Py = mean_Py / norm2;
    mean_PxPx = mean_PxPx / norm2;
    mean_PyPy = mean_PyPy / norm2;
    mean_angular_momentum = mean_angular_momentum / norm2;

    norm2 *= grid->delta_x * grid->delta_y;
    expected_values_updated = true;
}
Ejemplo n.º 11
0
void writeFrames(const Kinect::FrameSource::IntrinsicParameters& ip,const Kinect::FrameBuffer& color,const Kinect::MeshBuffer& mesh,const char* lwoFileName)
	{
	/* Create the texture file name: */
	std::string textureFileName(lwoFileName,Misc::getExtension(lwoFileName));
	textureFileName.append("-color.png");
	
	/* Write the color frame as a texture image: */
	{
	Images::RGBImage texImage(color.getSize(0),color.getSize(1));
	Images::RGBImage::Color* tiPtr=texImage.modifyPixels();
	const unsigned char* cfPtr=reinterpret_cast<const unsigned char*>(color.getBuffer());
	for(int y=0;y<color.getSize(1);++y)
		for(int x=0;x<color.getSize(0);++x,++tiPtr,cfPtr+=3)
			*tiPtr=Images::RGBImage::Color(cfPtr);
	
	Images::writeImageFile(texImage,textureFileName.c_str());
	}
	
	/* Open the LWO file: */
	IO::FilePtr lwoFile=IO::openFile(lwoFileName,IO::File::WriteOnly);
	lwoFile->setEndianness(Misc::BigEndian);
	
	/* Create the LWO file structure via the FORM chunk: */
	{
	IFFChunkWriter form(lwoFile,"FORM");
	form.write<char>("LWO2",4);
	
	/* Create the TAGS chunk: */
	{
	IFFChunkWriter tags(&form,"TAGS");
	tags.writeString("ColorImage");
	tags.writeChunk();
	}
	
	/* Create the LAYR chunk: */
	{
	IFFChunkWriter layr(&form,"LAYR");
	layr.write<Misc::UInt16>(0U);
	layr.write<Misc::UInt16>(0x0U);
	for(int i=0;i<3;++i)
		layr.write<Misc::Float32>(0.0f);
	layr.writeString("DepthImage");
	layr.writeChunk();
	}
	
	/* Create an index map for all vertices to omit unused vertices: */
	unsigned int* indices=new unsigned int[mesh.numVertices];
	for(unsigned int i=0;i<mesh.numVertices;++i)
		indices[i]=~0x0U;
	unsigned int numUsedVertices=0;
	
	/* Create the PNTS, BBOX and VMAP chunks in one go: */
	{
	typedef Kinect::FrameSource::IntrinsicParameters::PTransform PTransform;
	typedef PTransform::Point Point;
	typedef Geometry::Box<Point::Scalar,3> Box;
	
	IFFChunkWriter bbox(&form,"BBOX");
	IFFChunkWriter pnts(&form,"PNTS");
	IFFChunkWriter vmap(&form,"VMAP");
	
	/* Write the VMAP header: */
	vmap.write<char>("TXUV",4);
	vmap.write<Misc::UInt16>(2U);
	vmap.writeString("ColorImageUV");
	
	/* Process all triangle vertices: */
	Box pBox=Box::empty;
	const Kinect::MeshBuffer::Vertex* vertices=mesh.getVertices();
	const Kinect::MeshBuffer::Index* tiPtr=mesh.getTriangleIndices();
	for(unsigned int i=0;i<mesh.numTriangles*3;++i,++tiPtr)
		{
		/* Check if the triangle vertex doesn't already have an index: */
		if(indices[*tiPtr]==~0x0U)
			{
			/* Assign an index to the triangle vertex: */
			indices[*tiPtr]=numUsedVertices;
			
			/* Transform the mesh vertex to camera space using the depth projection matrix: */
			Point dp(vertices[*tiPtr].position.getXyzw());
			Point cp=ip.depthProjection.transform(dp);
			
			/* Transform the depth-space point to texture space using the color projection matrix: */
			Point tp=ip.colorProjection.transform(dp);
			
			/* Add the point to the bounding box: */
			pBox.addPoint(cp);
			
			/* Store the point and its texture coordinates: */
			pnts.writePoint(cp);
			vmap.writeVarIndex(numUsedVertices);
			for(int i=0;i<2;++i)
				vmap.write<Misc::Float32>(tp[i]);
			
			++numUsedVertices;
			}
		}
	
	/* Write the bounding box: */
	bbox.writeBox(pBox);
	
	/* Write the BBOX, PNTS, and VMAP chunks: */
	bbox.writeChunk();
	pnts.writeChunk();
	vmap.writeChunk();
	}
	
	/* Create the POLS chunk: */
	{
	IFFChunkWriter pols(&form,"POLS");
	pols.write<char>("FACE",4);
	const Kinect::MeshBuffer::Index* tiPtr=mesh.getTriangleIndices();
	for(unsigned int triangleIndex=0;triangleIndex<mesh.numTriangles;++triangleIndex,tiPtr+=3)
		{
		pols.write<Misc::UInt16>(3U);
		for(int i=0;i<3;++i)
			pols.writeVarIndex(indices[tiPtr[2-i]]);
		}
	pols.writeChunk();
	}
	
	/* Delete the vertex index map: */
	delete[] indices;
	
	/* Create the PTAG chunk: */
	{
	IFFChunkWriter ptag(&form,"PTAG");
	ptag.write<char>("SURF",4);
	for(unsigned int triangleIndex=0;triangleIndex<mesh.numTriangles;++triangleIndex)
		{
		ptag.writeVarIndex(triangleIndex);
		ptag.write<Misc::UInt16>(0U);
		}
	ptag.writeChunk();
	}
	
	/* Create the CLIP chunk: */
	{
	IFFChunkWriter clip(&form,"CLIP");
	clip.write<Misc::UInt32>(1U);
	
	/* Create the STIL chunk: */
	{
	IFFChunkWriter stil(&clip,"STIL",true);
	stil.writeString(textureFileName.c_str());
	stil.writeChunk();
	}
	
	clip.writeChunk();
	}
	
	/* Create the SURF chunk: */
	{
	IFFChunkWriter surf(&form,"SURF");
	surf.writeString("ColorImage");
	surf.writeString("");
	
	/* Create the SIDE subchunk: */
	{
	IFFChunkWriter side(&surf,"SIDE",true);
	side.write<Misc::UInt16>(3U);
	side.writeChunk();
	}
	
	/* Create the SMAN subchunk: */
	{
	IFFChunkWriter sman(&surf,"SMAN",true);
	sman.write<Misc::Float32>(Math::rad(90.0f));
	sman.writeChunk();
	}
	
	/* Create the COLR subchunk: */
	{
	IFFChunkWriter colr(&surf,"COLR",true);
	colr.writeColor(1.0f,1.0f,1.0f);
	colr.writeVarIndex(0U);
	colr.writeChunk();
	}
	
	/* Create the DIFF subchunk: */
	{
	IFFChunkWriter diff(&surf,"DIFF",true);
	diff.write<Misc::Float32>(1.0f);
	diff.writeVarIndex(0U);
	diff.writeChunk();
	}
	
	/* Create the LUMI subchunk: */
	{
	IFFChunkWriter lumi(&surf,"LUMI",true);
	lumi.write<Misc::Float32>(0.0f);
	lumi.writeVarIndex(0U);
	lumi.writeChunk();
	}
	
	/* Create the BLOK subchunk: */
	{
	IFFChunkWriter blok(&surf,"BLOK",true);
	
	/* Create the IMAP subchunk: */
	{
	IFFChunkWriter imap(&blok,"IMAP",true);
	imap.writeString("1");
	
	/* Create the CHAN subchunk: */
	{
	IFFChunkWriter chan(&imap,"CHAN",true);
	chan.write<char>("COLR",4);
	chan.writeChunk();
	}
	
	imap.writeChunk();
	}
	
	/* Create the PROJ subchunk: */
	{
	IFFChunkWriter proj(&blok,"PROJ",true);
	proj.write<Misc::UInt16>(5U);
	proj.writeChunk();
	}
	
	/* Create the IMAG subchunk: */
	{
	IFFChunkWriter imag(&blok,"IMAG",true);
	imag.writeVarIndex(1U);
	imag.writeChunk();
	}
	
	/* Create the VMAP subchunk: */
	{
	IFFChunkWriter vmap(&blok,"VMAP",true);
	vmap.writeString("ColorImageUV");
	vmap.writeChunk();
	}
	
	blok.writeChunk();
	}
	
	/* Write the SURF chunk: */
	surf.writeChunk();
	}
	
	/* Write the FORM chunk: */
	form.writeChunk();
	}
	}
Ejemplo n.º 12
0
void State::loadtxt(char *file_name) {
    ifstream input(file_name);
    int in_width = grid->global_no_halo_dim_x;
    int in_height = grid->global_no_halo_dim_y;
    complex<double> tmp;
    for(int i = 0; i < in_height; i++) {
        for(int j = 0; j < in_width; j++) {
            input >> tmp;

            if((i - grid->start_y) >= 0 && (i - grid->start_y) < grid->dim_y && (j - grid->start_x) >= 0 && (j - grid->start_x) < grid->dim_x) {
                p_real[(i - grid->start_y) * grid->dim_x + j - grid->start_x] = real(tmp);
                p_imag[(i - grid->start_y) * grid->dim_x + j - grid->start_x] = imag(tmp);
            }

            //Down band
            if(i < grid->halo_y && grid->mpi_coords[0] == grid->mpi_dims[0] - 1 && grid->periods[0] != 0) {
                if((j - grid->start_x) >= 0 && (j - grid->start_x) < grid->dim_x) {
                    p_real[(i + grid->dim_y - grid->halo_y) * grid->dim_x + j - grid->start_x] = real(tmp);
                    p_imag[(i + grid->dim_y - grid->halo_y) * grid->dim_x + j - grid->start_x] = imag(tmp);
                }
                //Down right corner
                if(j < grid->halo_x && grid->periods[1] != 0 && grid->mpi_coords[1] == grid->mpi_dims[1] - 1) {
                    p_real[(i + grid->dim_y - grid->halo_y) * grid->dim_x + j + grid->dim_x - grid->halo_x] = real(tmp);
                    p_imag[(i + grid->dim_y - grid->halo_y) * grid->dim_x + j + grid->dim_x - grid->halo_x] = imag(tmp);
                }
                //Down left corner
                if(j >= in_width - grid->halo_x && grid->periods[1] != 0 && grid->mpi_coords[1] == 0) {
                    p_real[(i + grid->dim_y - grid->halo_y) * grid->dim_x + j - (in_width - grid->halo_x)] = real(tmp);
                    p_imag[(i + grid->dim_y - grid->halo_y) * grid->dim_x + j - (in_width - grid->halo_x)] = imag(tmp);
                }
            }

            //Upper band
            if(i >= in_height - grid->halo_y && grid->periods[0] != 0 && grid->mpi_coords[0] == 0) {
                if((j - grid->start_x) >= 0 && (j - grid->start_x) < grid->dim_x) {
                    p_real[(i - (in_height - grid->halo_y)) * grid->dim_x + j - grid->start_x] = real(tmp);
                    p_imag[(i - (in_height - grid->halo_y)) * grid->dim_x + j - grid->start_x] = imag(tmp);
                }
                //Up right corner
                if(j < grid->halo_x && grid->periods[1] != 0 && grid->mpi_coords[1] == grid->mpi_dims[1] - 1) {
                    p_real[(i - (in_height - grid->halo_y)) * grid->dim_x + j + grid->dim_x - grid->halo_x] = real(tmp);
                    p_imag[(i - (in_height - grid->halo_y)) * grid->dim_x + j + grid->dim_x - grid->halo_x] = imag(tmp);
                }
                //Up left corner
                if(j >= in_width - grid->halo_x && grid->periods[1] != 0 && grid->mpi_coords[1] == 0) {
                    p_real[(i - (in_height - grid->halo_y)) * grid->dim_x + j - (in_width - grid->halo_x)] = real(tmp);
                    p_imag[(i - (in_height - grid->halo_y)) * grid->dim_x + j - (in_width - grid->halo_x)] = imag(tmp);
                }
            }

            //Right band
            if(j < grid->halo_x && grid->periods[1] != 0 && grid->mpi_coords[1] == grid->mpi_dims[1] - 1) {
                if((i - grid->start_y) >= 0 && (i - grid->start_y) < grid->dim_y) {
                    p_real[(i - grid->start_y) * grid->dim_x + j + grid->dim_x - grid->halo_x] = real(tmp);
                    p_imag[(i - grid->start_y) * grid->dim_x + j + grid->dim_x - grid->halo_x] = imag(tmp);
                }
            }

            //Left band
            if(j >= in_width - grid->halo_x && grid->periods[1] != 0 && grid->mpi_coords[1] == 0) {
                if((i - grid->start_y) >= 0 && (i - grid->start_y) < grid->dim_y) {
                    p_real[(i - grid->start_y) * grid->dim_x + j - (in_width - grid->halo_x)] = real(tmp);
                    p_imag[(i - grid->start_y) * grid->dim_x + j - (in_width - grid->halo_x)] = imag(tmp);
                }
            }
        }
    }
    input.close();
}
Ejemplo n.º 13
0
double complex::squaredNorm() const
{
    return pow(real(), 2)+pow(imag(), 2);
}
Ejemplo n.º 14
0
complex complex::square() const
{
    return complex(pow(real(), 2)-pow(imag(), 2), 2.0*real()*imag());
}
Ejemplo n.º 15
0
bool nf2ff::Write2HDF5(string filename)
{
	HDF5_File_Writer hdf_file(filename);

	//write mesh information
	hdf_file.SetCurrentGroup("/Mesh");
	size_t meshsize[1]={m_numTheta};
	if (hdf_file.WriteData(string("theta"),m_theta,1,meshsize)==false)
		return false;
	meshsize[0]=m_numPhi;
	if (hdf_file.WriteData(string("phi"),m_phi,1,meshsize)==false)
		return false;
	meshsize[0]=1;
	float rad[1]={m_radius};
	if (hdf_file.WriteData(string("r"),rad,1,meshsize)==false)
		return false;

	float attr_value = 2;
	hdf_file.WriteAtrribute("/Mesh", "MeshType", &attr_value, 1);

	//write field data
	size_t dim = 2;
	size_t pos = 0;
	size_t datasize[2]={m_numPhi,m_numTheta};
	size_t size = datasize[0]*datasize[1];
	double* buffer = new double[size];
	complex<double>** field_data;
	string field_names[2]={"E_theta", "E_phi"};
	for (int n=0;n<2;++n)
	{
		hdf_file.SetCurrentGroup("/nf2ff/" + field_names[n] + "/FD");
		for (size_t fn=0;fn<m_freq.size();++fn)
		{
			stringstream ss;
			ss << "f" << fn;
			pos = 0;
			if (n==0)
				field_data = GetETheta(fn);
			else
				field_data = GetEPhi(fn);
			for (size_t j=0;j<m_numPhi;++j)
				for (size_t i=0;i<m_numTheta;++i)
				{
					buffer[pos++]=real(field_data[i][j]);
				}
			if (hdf_file.WriteData(ss.str() + "_real",buffer,dim,datasize)==false)
			{
				delete[] buffer;
				cerr << "nf2ff::Write2HDF5: Error writing field data" << endl;
				return false;
			}

			pos = 0;
			for (size_t j=0;j<m_numPhi;++j)
				for (size_t i=0;i<m_numTheta;++i)
				{
					buffer[pos++]=imag(field_data[i][j]);
				}
			if (hdf_file.WriteData(ss.str() + "_imag",buffer,dim,datasize)==false)
			{
				delete[] buffer;
				cerr << "nf2ff::Write2HDF5: Error writing field data" << endl;
				return false;
			}
		}
	}

	//dump radiated power
	hdf_file.SetCurrentGroup("/nf2ff/P_rad/FD");
	for (size_t fn=0;fn<m_freq.size();++fn)
	{
		stringstream ss;
		ss << "f" << fn;
		pos = 0;
		double** field_data = GetRadPower(fn);
		for (size_t j=0;j<m_numPhi;++j)
			for (size_t i=0;i<m_numTheta;++i)
			{
				buffer[pos++]=field_data[i][j];
			}
		if (hdf_file.WriteData(ss.str(),buffer,dim,datasize)==false)
		{
			delete[] buffer;
			cerr << "nf2ff::Write2HDF5: Error writing field data" << endl;
			return false;
		}
	}
	delete[] buffer;

	//write frequency attribute
	hdf_file.WriteAtrribute("/nf2ff", "Frequency",m_freq);

	buffer = new double[m_freq.size()];
	//write radiated power attribute
	for (size_t fn=0;fn<m_freq.size();++fn)
		buffer[fn] = GetTotalRadPower(fn);
	hdf_file.WriteAtrribute("/nf2ff", "Prad",buffer,m_freq.size());
	delete[] buffer;

	//write max directivity attribute
	buffer = new double[m_freq.size()];
	for (size_t fn=0;fn<m_freq.size();++fn)
		buffer[fn] = GetMaxDirectivity(fn);
	hdf_file.WriteAtrribute("/nf2ff", "Dmax",buffer,m_freq.size());
	delete[] buffer;

	if (m_permittivity.size()>0)
	{
		buffer = new double[m_permittivity.size()];
		for (size_t n=0;n<m_permittivity.size();++n)
			buffer[n] = m_permittivity.at(n);
		hdf_file.WriteAtrribute("/nf2ff", "Eps_r",buffer,m_permittivity.size());
		delete[] buffer;
	}

	if (m_permeability.size()>0)
	{
		buffer = new double[m_permeability.size()];
		for (size_t n=0;n<m_permeability.size();++n)
			buffer[n] = m_permeability.at(n);
		hdf_file.WriteAtrribute("/nf2ff", "Mue_r",buffer,m_permeability.size());
		delete[] buffer;
	}

	return true;
}
KOKKOS_INLINE_FUNCTION
RealType abs (const complex<RealType>& x) {
  // FIXME (mfh 31 Oct 2014) Scale to avoid unwarranted overflow.
  return ::sqrt (real (x) * real (x) + imag (x) * imag (x));
}
Ejemplo n.º 17
0
Archivo: ovm_mpq.c Proyecto: pcpa/owl
void
ovm_q_atan2(oregister_t *l, oregister_t *r)
{
    switch (r->t) {
	case t_void:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = atan2(mpq_get_d(oqr(l)), 0.0);
	    }
	    else {
		mpfr_set_ui(orr(r), 0, thr_rnd);
		goto mpr;
	    }
	    break;
	case t_word:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = atan2(mpq_get_d(oqr(l)), r->v.w);
	    }
	    else {
		mpfr_set_si(orr(r), r->v.w, thr_rnd);
		goto mpr;
	    }
	    break;
	case t_float:
	    l->t = t_float;
	    l->v.d = atan2(mpq_get_d(oqr(l)), r->v.d);
	    break;
	case t_mpz:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = atan2(mpq_get_d(oqr(l)), mpz_get_d(ozr(r)));
	    }
	    else {
		mpfr_set_z(orr(r), ozr(r), thr_rnd);
		goto mpr;
	    }
	    break;
	case t_rat:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = atan2(mpq_get_d(oqr(l)), rat_get_d(r->v.r));
	    }
	    else {
		mpq_set_si(oqr(r), rat_num(r->v.r), rat_den(r->v.r));
		mpfr_set_q(orr(r), oqr(r), thr_rnd);
		goto mpr;
	    }
	    break;
	case t_mpq:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = atan2(mpq_get_d(oqr(l)), mpq_get_d(oqr(r)));
	    }
	    else {
		mpfr_set_q(orr(r), oqr(r), thr_rnd);
		goto mpr;
	    }
	    break;
	case t_mpr:
	mpr:
	    mpfr_set_q(orr(l), oqr(l), thr_rnd);
	    l->t = t_mpr;
	    mpfr_atan2(orr(l), orr(l), orr(r), thr_rnd);
	    break;
	case t_cdd:
	cdd:
	    l->t = t_cdd;
	    real(l->v.dd) = mpq_get_d(oqr(l));
	    imag(l->v.dd) = 0.0;
	    l->v.dd = catan(l->v.dd / r->v.dd);
	    check_cdd(l);
	    break;
	case t_cqq:
	    if (!cfg_float_format) {
		real(r->v.dd) = mpq_get_d(oqr(r));
		imag(r->v.dd) = mpq_get_d(oqi(r));
		goto cdd;
	    }
	    mpc_set_q_q(occ(r), oqr(r), oqi(r), thr_rndc);
	case t_mpc:
	    l->t = t_mpc;
	    mpc_set_q(occ(l), oqr(l), thr_rndc);
	    mpc_div(occ(l), occ(l), occ(r), thr_rndc);
	    mpc_atan(occ(l), occ(l), thr_rndc);
	    check_mpc(l);
	    break;
	default:
	    ovm_raise(except_not_a_number);
    }
}
KOKKOS_INLINE_FUNCTION
complex<RealType> conj (const complex<RealType>& x) {
  return complex<RealType> (real (x), -imag (x));
}
Ejemplo n.º 19
0
Archivo: ovm_mpq.c Proyecto: pcpa/owl
void
ovm_q_hypot(oregister_t *l, oregister_t *r)
{
    switch (r->t) {
	case t_void:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = fabs(mpq_get_d(oqr(l)));
	    }
	    else {
		mpfr_set_ui(orr(r), 0, thr_rnd);
		goto mpr;
	    }
	    break;
	case t_word:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = hypot(mpq_get_d(oqr(l)), r->v.w);
	    }
	    else {
		mpfr_set_si(orr(r), r->v.w, thr_rnd);
		goto mpr;
	    }
	    break;
	case t_float:
	    l->t = t_float;
	    l->v.d = hypot(mpq_get_d(oqr(l)), r->v.d);
	    break;
	case t_mpz:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = hypot(mpq_get_d(oqr(l)), mpz_get_d(ozr(r)));
	    }
	    else {
		mpfr_set_z(orr(r), ozr(r), thr_rnd);
		goto mpr;
	    }
	    break;
	case t_rat:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = hypot(mpq_get_d(oqr(l)), rat_get_d(r->v.r));
	    }
	    else {
		mpq_set_si(oqr(r), rat_num(r->v.r), rat_den(r->v.r));
		mpfr_set_q(orr(r), oqr(r), thr_rnd);
		goto mpr;
	    }
	    break;
	case t_mpq:
	    if (!cfg_float_format) {
		l->t = t_float;
		l->v.d = hypot(mpq_get_d(oqr(l)), mpq_get_d(oqr(r)));
	    }
	    else {
		mpfr_set_q(orr(r), oqr(r), thr_rnd);
		goto mpr;
	    }
	    break;
	case t_mpr:
	mpr:
	    l->t = t_mpr;
	    mpfr_set_q(orr(l), oqr(l), thr_rnd);
	    mpfr_hypot(orr(l), orr(l), orr(r), thr_rnd);
	    break;
	case t_cdd:
	cdd:
	    l->t = t_float;
	    l->v.d = hypot(mpq_get_d(oqr(l)),
			   hypot(real(r->v.dd), imag(r->v.dd)));
	    break;
	case t_cqq:
	    if (!cfg_float_format) {
		real(r->v.dd) = mpq_get_d(oqr(r));
		imag(r->v.dd) = mpq_get_d(oqi(r));
		goto cdd;
	    }
	    mpc_set_q_q(occ(r), oqr(r), oqi(r), thr_rndc);
	case t_mpc:
	    l->t = t_mpr;
	    mpc_set_q(occ(l), oqr(l), thr_rndc);
	    mpfr_hypot(ori(l), orr(l), ori(l), thr_rnd);
	    mpfr_hypot(orr(l), orr(r), ori(r), thr_rnd);
	    mpfr_hypot(orr(l), ori(l), orr(l), thr_rnd);
	    break;
	default:
	    ovm_raise(except_not_a_number);
    }
}
KOKKOS_INLINE_FUNCTION
complex<RealType1>
operator / (const complex<RealType1>& x, const RealType2& y) {
  return complex<RealType1> (real (x) / y, imag (x) / y);
}
Ejemplo n.º 21
0
//---------------------------------------------------------------------
//	Determine BER result
//---------------------------------------------------------------------
void qpsk_ber_test::ber_results(long received) {
  // For measuring simulation time
  float_type elapsed_time = 0;
  if ((received % modc == 0) && sync) {
    elapsed_time = difftime(time(NULL), start_time);
    if (received > 512) {
      std::cout << "Symbols = " << received;
      std::cout << " Errors = " << errors;
      std::cout << " BER = " << (float_type)errors / (float_type)received;
      std::cout << " Elpsd Time = " << elapsed_time / 60.0 << "(min)\n";
      std::cout.flush();
    }
    modc <<= 1;
  }
#ifdef KBHITD
  // you need to include some type of conio header file!!!!!!!
  if (kbhit()) {
#else
  // Replaces kbhit from conio.h
  if (std::cin.rdbuf()->in_avail()) {  // get() will not block
#endif
    elapsed_time = difftime(time(NULL), start_time);
    if (received > 512) {
      std::cout << "Symbols = " << received;
      std::cout << " Errors = " << errors;
      std::cout << " BER = " << (float_type)errors / (float_type)received;
      std::cout << " Elpsd Time = " << elapsed_time / 60.0 << "(min)\n";
      std::cout.flush();
    }
    std::cin.get();
  }
}
//**********************************************************************************
// Correlate received signal with reference PN and indicate when
// Synchronization is found by setting sync to +1 or -1.
// When synchronization is first found output is 2,
// otherwise it is the received bit multiplied by the
// reference PN bit.
//
long qpsk_ber_test::synchronize(long* received, complex<long> data) {
  const char thres = 57;  // Threshold for sync
  const char pnlen = 63;
  complex<long> out = 0;

  // Correlate with reference PN
  long tmp = ref.out();
  out = tmp * data;
  corr_sum += out;
  if ((*received % pnlen == 0) && (sync == 0)) {
    if (real(corr_sum) > thres) {
      rotate = complex<long>(1, 0);
      *received = 1;
      interval = 1;
      sync = 1;
    } else if (-real(corr_sum) > thres) {
      rotate = complex<long>(-1, 0);
      *received = 1;
      interval = 1;
      sync = 1;
    } else if (imag(corr_sum) > thres) {
      rotate = complex<long>(0, -1);
      *received = 1;
      interval = 1;
      sync = 1;
    } else if (-imag(corr_sum) > thres) {
      rotate = complex<long>(0, 1);
      *received = 1;
      interval = 1;
      sync = 1;
    } else {
      sync = 0;
      corr_sum = 0;  // Reset sum
      ref.out();     // Clock extra PN sample
      rotate = complex<long>(0, 0);
    }
  }
  // End correlation block
  // Count Errors
  if (sync != 0) errors += (real(out * rotate) == 1) ? 0 : 1;
  interval++;
  return (errors);
}
//**********************************************************************************
// Correlate received signal with reference PN and indicate when
// Synchronization is found by setting sync to +1 or -1.
// When synchronization is first found output is 2,
// otherwise it is the received bit multiplied by the
// reference PN bit.
//
long qpsk_ber_test::synchronise(long received, complex<double> data) {
  const char thres = 57;  // Threshold for sync
  const char pnlen = 63;
  long rcvd = received;
  complex<long> out = 0;

  // Correlate with reference PN
  long tmp = ref.out();
  out = tmp * complex<long>(data);
  corr_sum += out;
  if ((received % pnlen == 0) && (sync == 0)) {
    if (real(corr_sum) > thres) {
      rotate = complex<long>(1, 0);
      rcvd = 1;
      interval = 1;
      sync = 1;
    } else if (-real(corr_sum) > thres) {
      rotate = complex<long>(-1, 0);
      rcvd = 1;
      interval = 1;
      sync = 1;
    } else if (imag(corr_sum) > thres) {
      rotate = complex<long>(0, -1);
      rcvd = 1;
      interval = 1;
      sync = 1;
    } else if (-imag(corr_sum) > thres) {
      rotate = complex<long>(0, 1);
      rcvd = 1;
      interval = 1;
      sync = 1;
    } else {
      sync = 0;
      corr_sum = 0;  // Reset sum
      ref.out();     // Clock extra PN sample
      rotate = complex<long>(0, 0);
    }
  }
  // End correlation block
  // Count Errors
  if (sync != 0) errors += (real(out * rotate) == 1) ? 0 : 1;
  interval++;
  return (rcvd);
}
//
// Final result
//
void qpsk_ber_test::final_results(long received) {
  float_type elapsed_time = 0;
  if (sync != 0) {
    elapsed_time = difftime(time(NULL), start_time);
    std::cout << "Symbols = " << received;
    std::cout << " Errors = " << errors;
    std::cout << " Elpsd Time = " << elapsed_time / 60.0 << "(min)\n";
    std::cout << " BER = " << (float_type)errors / (float_type)received << "\n";
    std::cout.flush();
  } else {
    std::cout << "Synchronization with reference PN not found!\n";
    std::cout.flush();
  }
}
KOKKOS_INLINE_FUNCTION
bool operator == (const complex<RealType>& x, const complex<RealType>& y) {
  return real (x) == real (y) && imag (x) == imag (y);
}
int main()
{
    std::ofstream fout1("test1.dat");  // Flat Sky
    std::ofstream fout2("test2.dat");  // Spherical near equator
    std::ofstream fout3("test3.dat");  // Spherical around N pole.
    std::ofstream fout4("test4.dat");  // Test1 with random offsets
    std::ofstream fout4c("test4_centers.dat");  // Corresponding centers for test4.dat
    fout1.precision(12);
    fout2.precision(12);
    fout3.precision(12);
    fout4.precision(12);
    fout4c.precision(12);

    double ra0 = 0.; // RA, Dec of center for test2.
    double dec0 = 80.;

    const long ngal = 100000;
    const double rscale = 1.; // Scale radius in degrees.
    const double rmax = 5.; // In units of rscale

    // The functional form imprinted is purely radial:
    // gamma_t(r) = gamma0/r
    // kappa(r) = kappa0/r
    // n(r) ~ exp(-r^2/2)
    // where r is in units of rscale
    const double gamma0 = 1.e-3;
    const double kappa0 = 3.e-3;
    // Make sure gamma_t < 0.5
    const double rmin = gamma0/0.5;

    srand(1234); // To make it deterministic.
    // Normally for the Box-Muller Transformation, one would restrict rsq < 1
    // But we then want to clip the resulting distribution at rmax, so
    // rsq * fac^2 < rmax^2
    // rsq * (-2.*log(rsq)/rsq) < rmax^2
    // -2. * log(rsq) < rmax^2
    // rsq > exp(-rmax^2/2)
    const double rsqmin = exp(-rmax*rmax/2.);
    const double rsqmax = exp(-rmin*rmin/2.);
    //std::cout<<"rsq min/max = "<<rsqmin<<','<<rsqmax<<std::endl;

    double xdeg_min=0., xdeg_max=0., var_xdeg=0.;
    double ydeg_min=0., ydeg_max=0., var_ydeg=0.;

    for (long n=0; n<ngal; ++n) {
        double x,y,rsq;
        do {
            x = double(rand()) / RAND_MAX; // Random number from 0..1
            y = double(rand()) / RAND_MAX;
            //std::cout<<"x,y = "<<x<<','<<y<<std::endl;
            x = 2.*x-1.; // Now from -1..1
            y = 2.*y-1.;
            //std::cout<<"x,y => "<<x<<','<<y<<std::endl;
            rsq = x*x+y*y;
            //std::cout<<"rsq = "<<rsq<<std::endl;
        } while (rsq <= rsqmin || rsq >= rsqmax);
        // Use Box-Muller Transformation to convert to Gaussian distribution in x,y.
        double fac = sqrt(-2.*log(rsq)/rsq);
        x *= fac;
        y *= fac;

        double r = fac*sqrt(rsq);
        double theta = atan2(y,x);
        double g = gamma0 / r;
        double k = kappa0 / r;
        assert(g < 0.5);

        double xdeg = x*rscale;
        double ydeg = y*rscale;
        double rdeg = r*rscale;

        // Do some sanity checks:
        if (xdeg < xdeg_min) xdeg_min = xdeg;
        if (xdeg > xdeg_max) xdeg_max = xdeg;
        if (ydeg < ydeg_min) ydeg_min = ydeg;
        if (ydeg > ydeg_max) ydeg_max = ydeg;
        var_xdeg += xdeg*xdeg;
        var_ydeg += ydeg*ydeg;

        //
        // Flat sky:
        // 
        double g1 = -g * cos(2.*theta);
        double g2 = -g * sin(2.*theta);
        fout1 << xdeg <<"  "<< ydeg <<"  "<< g1 <<"  "<< g2 <<"  "<< k <<std::endl;


        // With offsets in position:
        double dx = 2.*double(rand()) / RAND_MAX - 1.; // Random number from -1..1
        double dy = 2.*double(rand()) / RAND_MAX - 1.;
        dx *= rscale;
        dy *= rscale;
        fout4 << xdeg + dx <<"  "<< ydeg + dy <<"  "<< g1 <<"  "<< g2 <<"  "<< k <<std::endl;
        fout4c << dx <<"  "<< dy <<"  1. "<<std::endl;

        // 
        // Spherical near equator:
        //

        // Use spherical triangle with A = point, B = (ra0,dec0), C = N. pole
        // a = Pi/2-dec0
        // c = 2*atan(r/2)
        // B = Pi/2 - theta

        // Solve the rest of the triangle with spherical trig:
        double c = 2.*atan( (rdeg*M_PI/180.) / 2.);
        double a = M_PI/2. - (dec0*M_PI/180.);
        double B = x > 0 ? M_PI/2. - theta : theta - M_PI/2.;
        if (B < 0) B += 2.*M_PI;
        if (B > 2.*M_PI) B -= 2.*M_PI;
        double cosb = cos(a)*cos(c) + sin(a)*sin(c)*cos(B);
        double b = std::abs(cosb) < 1. ? acos(cosb) : 0.;
        double cosA = (cos(a) - cos(b)*cos(c)) / (sin(b)*sin(c));
        double A = std::abs(cosA) < 1. ? acos(cosA) : 0.;
        double cosC = (cos(c) - cos(a)*cos(b)) / (sin(a)*sin(b));
        double C = std::abs(cosC) < 1. ? acos(cosC) : 0.;

        //std::cout<<"x,y = "<<x<<','<<y<<std::endl;
        //std::cout<<"a = "<<a<<std::endl;
        //std::cout<<"b = "<<b<<std::endl;
        //std::cout<<"c = "<<c<<std::endl;
        //std::cout<<"A = "<<A<<std::endl;
        //std::cout<<"B = "<<B<<std::endl;
        //std::cout<<"C = "<<C<<std::endl;

        // Compute ra,dec from these.
        // Note: increasing x is decreasing ra.  East is left on the sky!
        double ra = x>0 ? -C : C;
        double dec = M_PI/2. - b;
        ra *= 180. / M_PI;
        dec *= 180. / M_PI;
        ra += ra0;
        //std::cout<<"ra = "<<ra<<std::endl;
        //std::cout<<"dec = "<<dec<<std::endl;

        // Rotate shear relative to local west
        std::complex<double> gamma(g1,g2);
        double beta = M_PI - (A+B);
        if (x > 0) beta = -beta;
        //std::cout<<"gamma = "<<gamma<<std::endl;
        //std::cout<<"beta = "<<beta<<std::endl;
        std::complex<double> exp2ibeta(cos(2.*beta),sin(2.*beta));
        gamma *= exp2ibeta;
        //std::cout<<"gamma => "<<gamma<<std::endl;
        fout2 << ra <<"  "<< dec <<"  "<< real(gamma) <<"  "<<imag(gamma) <<"  "<<k <<std::endl;

        //
        // Spherical around N pole
        //

        dec = 90. - c * 180./M_PI;
        ra = theta * 12. / M_PI;
        fout3 << ra <<"  "<< dec <<"  "<< g <<"  "<<0. <<"  "<<k <<std::endl;
    }
    var_xdeg /= ngal;
    var_ydeg /= ngal;
    std::cout<<"Min/Max x = "<<xdeg_min<<"  "<<xdeg_max<<std::endl;;
    std::cout<<"Min/Max y = "<<ydeg_min<<"  "<<ydeg_max<<std::endl;;
    std::cout<<"sqrt(Var(x)) = "<<sqrt(var_xdeg)<<std::endl;
    std::cout<<"sqrt(Var(y)) = "<<sqrt(var_ydeg)<<std::endl;

    // Make random catalogs
    std::ofstream foutr1("rand1.dat");
    std::ofstream foutr2("rand2.dat");
    std::ofstream foutr3("rand3.dat");
    foutr1.precision(12);
    foutr2.precision(12);
    foutr3.precision(12);
    xdeg_min=xdeg_max=var_xdeg=0.;
    ydeg_min=ydeg_max=var_ydeg=0.;
    for (long n=0; n<10*ngal; ++n) {
        double x,y,rsq;
        do {
            x = double(rand()) / RAND_MAX; // Random number from 0..1
            y = double(rand()) / RAND_MAX;
            x = 2.*x-1.; // Now from -1..1
            y = 2.*y-1.;
            rsq = x*x+y*y;
        } while (rsq >= 1.);
        x *= rmax;
        y *= rmax;

        double r = rmax*sqrt(rsq);
        double theta = atan2(y,x);
        double xdeg = x*rscale;
        double ydeg = y*rscale;
        double rdeg = r*rscale;

        // Do some sanity checks:
        if (xdeg < xdeg_min) xdeg_min = xdeg;
        if (xdeg > xdeg_max) xdeg_max = xdeg;
        if (ydeg < ydeg_min) ydeg_min = ydeg;
        if (ydeg > ydeg_max) ydeg_max = ydeg;
        var_xdeg += xdeg*xdeg;
        var_ydeg += ydeg*ydeg;


        //
        // flat sky:
        // 
        foutr1 << xdeg <<"  "<< ydeg << std::endl;

        // 
        // Spherical near equator:
        //

        double c = 2.*atan( (rdeg*M_PI/180.) / 2.);
        double a = M_PI/2. - (dec0*M_PI/180.);
        double B = x > 0 ? M_PI/2. - theta : theta - M_PI/2.;
        if (B < 0) B += 2.*M_PI;
        if (B > 2.*M_PI) B -= 2.*M_PI;
        double cosb = cos(a)*cos(c) + sin(a)*sin(c)*cos(B);
        double b = std::abs(cosb) < 1. ? acos(cosb) : 0.;
        double cosC = (cos(c) - cos(a)*cos(b)) / (sin(a)*sin(b));
        double C = std::abs(cosC) < 1. ? acos(cosC) : 0.;

        double ra = x>0 ? -C : C;
        double dec = M_PI/2. - b;
        ra *= 180. / M_PI;
        dec *= 180. / M_PI;
        ra += ra0;

        foutr2 << ra <<"  "<< dec <<std::endl;

        //
        // Spherical around N pole
        //

        dec = 90. - c * 180./M_PI;
        ra = theta * 12. / M_PI;
        foutr3 << ra <<"  "<< dec <<std::endl;
    }
    var_xdeg /= ngal;
    var_ydeg /= ngal;
    std::cout<<"For randoms:\n";
    std::cout<<"Min/Max x = "<<xdeg_min<<"  "<<xdeg_max<<std::endl;;
    std::cout<<"Min/Max y = "<<ydeg_min<<"  "<<ydeg_max<<std::endl;;
    std::cout<<"sqrt(Var(x)) = "<<sqrt(var_xdeg)<<std::endl;
    std::cout<<"sqrt(Var(y)) = "<<sqrt(var_ydeg)<<std::endl;
    return 0;
}
KOKKOS_INLINE_FUNCTION
bool operator != (const std::complex<RealType>& x, const complex<RealType>& y) {
  return std::real (x) != real (y) || std::imag (x) != imag (y);
}
void Jacobi(const Array2 < dcomplex > & Ain, Array1 <doublevar> & evals, Array2 < dcomplex > & evecs)
{
  //assert(Ain.nr == Ain.nc);
  //assert(Ain.hermitian);

  
  //numerical recepies Jacobi transfomation eigen value solver
  const int n = Ain.dim[0];
  
  int p,q;
  doublevar fabsApq,fabsApp,fabsAqq;
  doublevar a,c,blen,sitheta;
  dcomplex b;
  doublevar t,zeta;
  doublevar alpha,stau;
  dcomplex beta,betastar;
  dcomplex  zp,zq;

  const int MAXSWEEP=100;

  /* local copy to work on */
  Array2 < dcomplex > A(n,n);

  /* Copy Ain to A */
  for (int i=0; i < n; i++)
    for (int j=0; j < n; j++) {
      A(i,j) = Ain(i,j);
      //cout <<  A(i,j).imag()<<endl;
    }

  /* Set evecs to identity */
  for (int i=0; i < n; i++)
    for (int j=0; j < n; j++) {
      if (i==j) evecs(i,j) = 1.0;
      else evecs(i,j) = 0.0;
    }

  int sweep;
  for (sweep=0; sweep < MAXSWEEP; sweep++) {
    /* S = sum of abs of real and imag of off diag terms */
    /* maxoffdiag is maximum size of off-diagonal element, and (p,q)
     * will contain its coordinates in the matrix A */
    doublevar maxoffdiag = 0.0;
    doublevar S = 0.0;
    for (int i=0; i < n; i++)
      for (int j=i+1; j < n; j++) {
        const doublevar temp = fabs(real(A(i,j)))+fabs(imag(A(i,j)));
        S += temp;
        if (temp >= maxoffdiag) {
          maxoffdiag = temp;
          p = i;
          q = j;
        }
      }
    if (maxoffdiag == 0.0) break;
    // If we're done to machine precision, go home!
    fabsApp = fabs(real(A(p,p)))+fabs(imag(A(p,p)));
    fabsAqq = fabs(real(A(q,q)))+fabs(imag(A(q,q)));
    if ( (maxoffdiag+fabsApp==fabsApp) && (maxoffdiag+fabsAqq==fabsAqq) )
      break;

    // set threshold
    doublevar thresh = 0.0;
    if (sweep < 5) thresh = 0.4*S/(n*n);

    // Loop over off diagonal terms of A in upper triangle: p < q
    for (int p=0; p < n; p++)
      for (int q=p+1; q < n; q++) {
        // If A(p,q) is too small compared to A(p,p) and A(q,q),
        // skip the rotation
        fabsApq = fabs(real(A(p,q)))+fabs(imag(A(p,q)));
        fabsApp = fabs(real(A(p,p)))+fabs(imag(A(p,p)));
        fabsAqq = fabs(real(A(q,q)))+fabs(imag(A(q,q)));
        if ( (fabsApq+fabsApp==fabsApp) && (fabsApq+fabsAqq==fabsAqq) )
          continue;
      
        // If A(p,q) is smaller than the threshold, then also skip
        // the rotation
        if (fabsApq <= thresh)
          continue;

        // the 2x2 matrix we diagonalize is [ [a b] ; [conj(b) a] ]
        a = real(A(p,p));
        c = real(A(q,q));
        b = A(p,q);
        blen = abs(b);
        zeta = (c-a)/(2.0*blen);

        // t = sgn(zeta)/(|zeta|+sqrt(zeta^2+1)), but if zeta is too
        // huge, then we set t = 1/(2*zeta)
        if ( fabs(zeta)>1.0e200 )
          t = 1/(2.0*zeta);
        else {
          t = 1.0/(fabs(zeta)+sqrt(zeta*zeta+1.0));
          if (zeta<0.0) t = -t;
        }

        /* The matrix we use to diagonalize the 2x2 block above is
         * [ [alpha beta] ; [-conj(beta) alpha] ] 
         * where alpha is real and positive and alpha = cos(theta)
         * and beta = sin(theta)*b/|b|.
         * The angle theta is chosen to diagonalize the 2x2 block.
         * The relevant formula are sin(theta)=cos(theta)*t and
         * cos(theta)=1/sqrt(1+t^2).
         * stau = (1-alpha) cleverly written. */
        alpha = 1.0/sqrt(t*t+1.0);
        sitheta = t*alpha;
        stau = sitheta*sitheta/(1.0+alpha);
        beta = b*sitheta/blen;
        betastar = conj(beta);

        /* Now we update the elements of A: */
        /* This involves chaning the p'th and q'th column of A */
        for (int i=0; i < n; i++) {
          if (i==p) {
            A(i,p) -= blen*t;
            A(i,q) = 0.0;
          }
          else if (i==q) {
            A(i,p) = 0.0;
            A(i,q) += blen*t;
          }
          else {
            zp = A(i,p);
            zq = A(i,q);
            A(i,p) -= stau*zp + betastar*zq;
            A(i,q) += beta*zp - stau*zq;
            A(p,i) = conj(A(i,p));
            A(q,i) = conj(A(i,q));
          }
        }
        /*
        for (int i=0; i < n; i++){
          for (int j=i; j < n; j++) {
            if(fabs(A(i,j).real())>1e-6)
              cout <<  A(i,j).real()<<"  ";
            else 
              cout <<"0  ";
          }
          cout << endl;
        }
        */

        /* Now we must update the eigenvector matrix with this
         * rotation:  evecs <- evecs*P_pq.
         * Update p'th and q'th column of evecs */
        for (int i=0; i < n; i++) {
          zp = evecs(i,p);
          zq = evecs(i,q);
          evecs(i,p) = alpha*zp - betastar*zq;
          evecs(i,q) = beta*zp  + alpha*zq;
        }
      } /* (p,q) rotation loop */
  } /* end of sweep loop */
    
  if (sweep == MAXSWEEP) {
    cout << endl <<"Warning:  Jacobi() needs more than "<<MAXSWEEP <<" sweeps "<<endl;
  }
  
  for (int i=0; i < n; i++) {
    evals[i] = real(A(i,i));
    //cout << evals[i]<<endl;
  }

  // sort eigs and evecs by ascending eigenvalue
  Array1 <int> list(n); 
  for (int i=0; i < n; i++) 
    list[i] = i;
  
  for (int i=1; i < n; i++) {
    const double temp = evals[i];
    int j;
    for (j=i-1; j>=0 && evals[j]<temp; j--) {
      evals[j+1] = evals[j];
      list[j+1] = list[j];
    }
    evals[j+1] = temp;
    list[j+1] = i;
  }
  
  A = evecs;
  for (int i=0; i < n; i++)
    for (int j=0; j < n; j++)
      evecs(i,j) = A(i,list[j]);
  
}
KOKKOS_INLINE_FUNCTION
bool operator != (const complex<RealType1>& x, const RealType2& y) {
  return real (x) != y || imag (x) != static_cast<RealType1> (0.0);
}
Ejemplo n.º 27
0
 bool complex::is_imag() const
 {
     return ::fabs(real()/imag()) < GSLEPS;
 }
Ejemplo n.º 28
0
    /**
     * @brief    Backward transform
     *
     * @param  m To transform
     * @return   Transform
     */
    virtual Matrix<T> Adjoint (const MatrixType<T>& m) const {

        Vector<size_t> N = m_N;
        NFFTRType* tmpd;
        RT* tmpt;

        if (m_have_b0)
            N.pop_back();
        if (m_3rd_dim_cart && m_ncart > 1) // Cartesian FT 3rd dim
            N.push_back(m_ncart);

        Matrix<T> out (N);
        for (size_t i = 0; i < m_ncart; ++i) {

            tmpd = (NFFTRType*) m_solver.y;

            size_t os = i*m_M;
            for (size_t j = 0; j < m_M; ++j) {
                tmpd[2*j+0] = real(m[os+j]);
                tmpd[2*j+1] = imag(m[os+j]);
            }

            if (m_have_b0)
                NFFTTraits<NFFTType>::ITrafo
                ((B0Plan&) m_b0_plan, (Solver&) m_solver, m_maxit, m_epsilon);
            else
                NFFTTraits<NFFTType>::ITrafo
                ((Plan&)    m_plan,   (Solver&) m_solver, m_maxit, m_epsilon);

            tmpd = (NFFTRType*) m_solver.f_hat_iter;
            tmpt = (RT*) out.Ptr() + i*m_imgsz;

            std::copy (tmpd, tmpd+m_imgsz, tmpt);

            //TODO: b0 not 2D+1D+1D
            if (m_have_b0)
                for (size_t j = 0; j < out.Size(); ++j)
                    out[j + i*m_imgsz / 2] *= std::polar<RT>((RT)1.,
                                              (RT)(-2. * PI * m_ts * m_b0[j] * m_w));

        }

        /*        if (m_3rd_dim_cart && m_ncart > 1) { // Cartesian FT 3rd dim
                	int n = static_cast<int>(m_ncart);
                	out = permute (out, 2, 0, 1);
                	size_t cent = std::ceil(.5*m_ncart);
                	Matrix<T> tmp;
                	for (size_t i = 0; i < m_imgsz/2; ++i) { // fftshift colums
        				tmp = Column (out,i);
        				std::rotate(tmp.Begin(), tmp.Begin()+cent, tmp.End());
        				Column (out, i, tmp);
                	}
                	CartPlan cp = FTTraits<T>::DFTPlanMany (1, &n, m_imgsz/2,
                			(FTType*)out.Ptr(),	(FTType*)out.Ptr(), FFTW_BACKWARD);
                	FTTraits<T>::Execute(cp);
                	FTTraits<T>::Destroy(cp);
                	for (size_t i = 0; i < m_imgsz/2; ++i) { // fftshift colums
        				tmp = Column (out,i);
        				std::rotate(tmp.Begin(), tmp.Begin()+cent, tmp.End());
        				Column (out, i, tmp);
                	}
                	out = permute (out, 1, 2, 0)/sqrt((RT)m_ncart);
                    }*/

        return out;

    }
Ejemplo n.º 29
0
 bool operator < (const P& a, const P& b) {
     return real(a) != real(b) ? real(a) < real(b) : imag(a) < imag(b);
 }
Ejemplo n.º 30
0
// #include"reaction.h"
int main(){

////////Input Parameters of the potential (fit parameters) /////
std::string parameters_filename="Input.inp";

NuclearParameters Nu = read_nucleus_parameters( "Input/nca40.inp" );

double Ef=Nu.Ef;
int lmax=6;
double z0=20.0;
double zp0;
double A0=40.0;
double tz=-0.5;

int type=1;
int mvolume = 4;
int AsyVolume = 1;

double A = 40.0;

if (tz>0) { zp0=1;}
else {zp0=0;}

double ph_gap = Nu.ph_gap;
cout<<"ph_gap = "<<Nu.ph_gap<<endl;
double  rStart = .05;
double  rmax = 12.;
double  ham_pts = 180; 

double  rdelt = rmax / ham_pts;

//THIS IS ANOTHER CHANGE FROM THE OLD TOO////////////////
double  rdelt_p = rdelt / 1.025641026;

        // Construct Parameters Object
        Parameters p = get_parameters( parameters_filename, Nu.A, Nu.Z, zp0 );

        // Construct Potential Object
        pot pottt = get_bobs_pot2( type, mvolume, AsyVolume, tz, Nu, p );
	pot * pott = &pottt;

        // store coulomb potential in order to compare with




 boundRspace initiate(rmax , ham_pts , Ef, ph_gap , lmax , Nu.Z , zp0 , Nu.A , pott);


  
 double Elower = -11.61818;
 double Eupper = -9.4;
 double jj = .5;
 int ll = 0;
 int Ifine = 1;
 initiate.searchNonLoc( Elower, Eupper, jj,  ll,  Ifine);
 initiate.exteriorWaveFunct(ll);
 initiate.normalizeWF();


double tol=.01;
double estart=Ef;

///// Making rmesh///

//THIS IS THE DIFFERENCE FROM SKYRMEOLD////////////////////////////////
//vector <double> rmesh_p = initiate.make_rmesh();
std::vector<double> rmesh_p= initiate.make_rmesh_point();
std::vector<double> rmesh= initiate.make_rmesh();

// Create momentum space grid
std::vector<double> kmesh;
std::vector<double> kweights;
double const kmax = 5.0;
int const kpts = rmesh.size();
kmesh.resize( kpts );
kweights.resize( kpts );
GausLeg( 0., kmax, kmesh, kweights );

double J =0.5;

double Emax=2*-4.7;
double Emin=-200.0 + Emax;

std::ofstream filee("waves/neutron/natural/wave.out");
std::cout<<Elower<<std::endl;

//Generating the propagator

std::vector< lj_eigen_t > bound_levels = initiate.get_bound_levels( rmesh, tol );

std::vector< mesh_t > emesh_vec =
        initiate.get_emeshes( rmesh, Emin, Emax, bound_levels );

cout<<"emesh_vec = "<<emesh_vec.size()<<endl;

std::vector< prop_t > prop_vec = initiate.get_propagators( rmesh, emesh_vec );

double onum=0.0;
double num=0.0;
double part=0;
double kpart=0;
vector<double> denk;
denk.assign( kmesh.size(), 0 );
vector<double> k_dist;
k_dist.assign( kmesh.size(), 0 );
vector <double> natden;
natden.assign(rmesh.size(),0);
vector <double> natdenk;
natdenk.assign(kmesh.size(),0);
vector <double> ktest;
ktest.assign(kmesh.size(),0);
vector <double> diag;
diag.assign(kmesh.size(),0);

double dom=0;
double expo=0;

int Nmax=5;

string stable = "waves/neutron/natural/table.txt";
ofstream ftable(stable.c_str());

string presky = "waves/neutron/data/n";

vector<double> kdist;
kdist.assign(rmesh.size(),0);
lmax=0;
//Starting loop over L and J to go through all the orbitals
for(int L=0;L<lmax+1;L++){
	for(int s=0;s<2;s++){	
		J=L-0.5+s;
		if(J<0){
			J=0.5;
			s=1;
		}	
	
		cout<<"L = "<<L<<" J = "<<J<<endl;

		string jlab;
		if(J==0.5){
			jlab="12";
		}else if(J==1.5){
			jlab="32";
		}else if(J==2.5){
			jlab="52";
		}else if(J==3.5){
			jlab="72";
		}else if(J==4.5){
			jlab="92";
		}else if(J==5.5){
			jlab="112";
		}else if(J==6.5){
			jlab="132";
		}

		string llab;
		if(L==0){
			llab="s";
		}else if(L==1){
			llab="p";
		}else if(L==2){
			llab="d";
		}else if(L==3){
			llab="f";
		}else if(L==4){
			llab="g";
		}else if(L==5){
			llab="h";
		}else if(L==6){
			llab="i";
		}

/*
		int Nmax=10;
		if(L>1){
			Nmax=9;
		}
		if(L>3){
			Nmax=8;
		}
		if(L==6 && J == 5.5){
			Nmax=7;
		}	
*/
		Nmax=4;
		if(L>3) Nmax = 1;


		int Mmax=Nmax;


		ftable<<endl;
		ftable<<llab<<jlab<<endl;
		ftable<<"     ";
		for(int i=0;i<Mmax;i++){
			ftable<<i<<"            ";
		}
		ftable<<endl;

		string dest = "waves/neutron/natural/";

		int index=initiate.index_from_LJ(L,J);

		const prop_t &propE = prop_vec.at(index);

		const mesh_t &emesh = emesh_vec.at(index);

// Create Bessel Function matrix in k and r
    matrix_t bess_mtx( kmesh.size(), rmesh.size() );
		bess_mtx.clear();
		matrix_t bess_mtx_sky(kmesh.size(),rmesh.size());
		bess_mtx_sky.clear();
    for( unsigned int nk = 0; nk < kmesh.size(); ++nk ) {
	    for( unsigned int nr = 0; nr < rmesh.size(); ++nr ) {
	      double rho = kmesh[nk] * rmesh_p[nr];
        bess_mtx( nk, nr ) = gsl_sf_bessel_jl( L, rho );
				bess_mtx_sky(nk,nr) = gsl_sf_bessel_jl(L, kmesh[nk]*rmesh[nr]);
      }
    }		

		matrix_t d_mtx( rmesh.size(), rmesh.size() ); // density matrix
		d_mtx.clear();

//Remember that propE is actually G*r*r'*rdelt
		for(unsigned int n=0;n<emesh.size();++n){	
			double Edelt=emesh[n].second;
		  for( unsigned int i = 0; i < rmesh.size(); ++i ) {
				for( unsigned int j = 0; j < rmesh.size(); ++j ) {
					d_mtx(i,j) -= Edelt * imag(propE[n](i,j)) / M_PI;  
				} 
			} 
		}		

		const lj_eigen_t &levels = bound_levels.at(index);


//this adds the QP peaks to the particle number
		for ( unsigned int N = 0; N < levels.size(); ++N ){   
    	if ( ( levels[N].first <= Ef ) && 
      ( levels[N].first > Emax ) ) {
      	double QPE = levels[N].first;
      	const std::vector<double> &QPF = levels[N].second;
      	double S = initiate.sfactor( rmesh, QPE, L, J, QPF );
				for ( unsigned int i = 0; i < rmesh.size(); ++i ) {
					for(int j=0;j<rmesh.size();j++){
	          d_mtx(i,j) +=  S * QPF[i] * QPF[j] * rmesh[i]*rmesh[j]*rdelt;
          }
				}
			}
		}

		

		matrix_t k_mtx( rmesh.size(), rmesh.size() ); // density matrix
		k_mtx.clear();
		matrix_t mtx(rmesh.size(),rmesh.size() );
		mtx.clear();
		matrix_t diff_mtx(rmesh.size(),rmesh.size());
		diff_mtx.clear();
		matrix_t r_mtx( rmesh.size(), rmesh.size() ); // testing to see if this is the same as the original
		r_mtx.clear();

		double maxR = rmesh[rmesh.size()-1];
		double minR = rmesh[0];

	/*		for(int i=0;i<rmesh.size();i++){
			for(int j=0;j<rmesh.size();j++){
				//d_mtx(i,j) = exp(-pow(rmesh[i]-rmesh[j],2));
				//mtx(i,j) = (1.0 / pow(kmesh[i]*kmesh[j],2) ) * (cos(kmesh[i]*maxR) - cos(kmesh[i]*minR) ) * (cos(kmesh[j]*maxR) - cos(kmesh[i]*minR) ) * (2.0/M_PI);
			}
			f4[i] = mtx(i,i);
		}  */

		for(int i=0;i<rmesh.size();i++){
			if(i%30==0) cout<<i<<endl;
			for(int j=0;j<rmesh.size();j++){
				double kd=0;
				double kr;
				double kr2;
				for(int ii=0;ii<rmesh.size();ii++){
					for(int jj=0;jj<rmesh.size();jj++){
						//dmtx already has r*r'*dr
						kd += d_mtx(ii,jj) * bess_mtx(i,ii) * bess_mtx(j,jj) /( rmesh[ii] * rmesh[jj] * rdelt) * pow( rdelt_p * rmesh_p[ii] * rmesh_p[jj], 2) * (2.0/M_PI);
						//kd += d_mtx(ii,jj) * bess_mtx(i,ii) * bess_mtx(j,jj) * pow(rdelt * rmesh[ii] * rmesh[jj],2) * (2.0/M_PI);
						kr = kmesh[i] * rmesh[ii];
						kr2 = kmesh[j] * rmesh[jj];
						//kd += d_mtx(ii,jj) * sin(kr)/kr * sin(kr2)/kr2 * pow(rdelt * rmesh[ii] * rmesh[jj], 2) * (2.0/M_PI);
						//kd += d_mtx(ii,jj) * sin(kr)/kr * sin(kr2)/kr2 / ( rmesh[ii] * rmesh[jj] * rdelt) * pow( rdelt_p * rmesh_p[ii] * rmesh_p[jj], 2) * (2.0/M_PI);
					}
				}
			//including this for diagonalization
			k_mtx(i,j) = kd * kmesh[i] * kmesh[j] * kweights[i];			
			}
			//f2[i] = k_mtx(i,i);
			kdist[i] += k_mtx(i,i) * (2*J+1) / (4*M_PI);
		}

		for(int i=0;i<rmesh.size();i++){
			if(i%30==0) cout<<i<<endl;
			for(int j=0;j<rmesh.size();j++){
				double kd=0;
				double kr;
				double kr2;
				for(int ii=0;ii<rmesh.size();ii++){
					for(int jj=0;jj<rmesh.size();jj++){
						//already includes kk'dk
						kd += k_mtx(ii,jj) * bess_mtx(ii,i) * bess_mtx(jj,j) * kmesh[ii] * kmesh[jj] * kweights[jj] * (2.0/M_PI);
					}
				}
			//including this for diagonalization
			r_mtx(i,j) = kd * rmesh[i] * rmesh[j] * rdelt;			
			}
		}


		vector <eigen_t> eig = initiate.real_eigvecs(d_mtx);
		vector <eigen_t> eigr = initiate.real_eigvecs(r_mtx);
		vector <eigen_t> eigk = initiate.real_eigvecs(k_mtx);
		vector <eigen_t> eigm = initiate.real_eigvecs(mtx);

		ofstream diff("waves/diff.txt");
		
		for(int i=0;i<rmesh.size();i++){
			diff<<rmesh[i]<<" "<<eig[rmesh.size()-1].second[i]/rmesh[i]<<" "<<eigr[rmesh.size()-1].second[i]/rmesh[i]<<endl;
		}


		cout<<"maxR = "<<maxR<<endl;
		cout<<"minR = "<<minR<<endl;
		cout<<"kmesh[10] = "<<kmesh[100]<<endl;

		double eignorm=0;
		double reignorm=0;
		double keignorm=0;

		ofstream feval("waves/evals.txt");
		for(int i=0;i<rmesh.size();i++){
			double spot=rmesh.size()-1-i;
			feval<<eig[spot].first<<" "<<eigr[spot].first<<endl;
			eignorm += pow(eig[spot].first,2);
			reignorm += pow(eigr[spot].first,2);
			keignorm += pow(eigk[spot].first,2);
		}

	//	cout<<"eigval d_mtx[0] = "<<eig[0].first<<endl;
		cout<<"eigval d_mtx[N] = "<<eig[rmesh.size()-1].first<<endl;
		cout<<"eigval r_mtx[N] = "<<eigr[rmesh.size()-1].first<<endl;
	//	cout<<"eigval k_mtx[0] = "<<eigk[0].first<<endl;
		cout<<"eigval k_mtx[N] = "<<eigk[rmesh.size()-1].first<<endl;
		cout<<"eigval mtx[N] = "<<eigm[rmesh.size()-1].first<<endl;
		cout<<"k_mtx(10,10) = "<<k_mtx(100,100)<<endl;
		cout<<"mtx(10,10) = "<<mtx(100,100)<<endl;

		vector <double> f(rmesh.size());
		vector <double> f2(rmesh.size());
		vector <double> f3(rmesh.size());
		vector <double> f4(rmesh.size());
		for(int i=0;i<rmesh.size();i++){
			f[i] = eig[rmesh.size()-1].second[i]/rmesh_p[i]; 
		}

		double fk;

		for(int i=0;i<rmesh.size();i++){
			fk=0;
			for(int j=0;j<rmesh.size();j++){
				fk += f[j] * sin(rmesh[j] * kmesh[i])/(rmesh[j]*kmesh[i]) * pow(rmesh[j],2) * rdelt * sqrt(2.0/M_PI);
			}
			f2[i] = fk;
			f4[i] = 1.0/pow(kmesh[i],2) * (cos(minR*kmesh[i]) - cos(maxR*kmesh[i]) );
		}

		for(int i=0;i<rmesh.size();i++){
			fk=0;
			for(int j=0;j<rmesh.size();j++){
				fk += f2[j] * sin(rmesh[i] * kmesh[j])/(rmesh[i]*kmesh[j]) * pow(kmesh[j],2) * kweights[j] * sqrt(2.0/M_PI);
			}
			f3[i] = fk;
		}
				
		ofstream compk("waves/compk.txt");
		for(int i=0;i<rmesh.size();i++){
			compk<<kmesh[i]<<" "<<f2[i]<<" "<<f4[i]<<endl;
		}

		ofstream compr("waves/compr.txt");
		for(int i=0;i<rmesh.size();i++){
			compr<<rmesh[i]<<" "<<f[i]<<" "<<f3[i]<<endl;
		}

		double ksum=0;
		double rsum=0;

		for(int i=0;i<kmesh.size()-1;i++){

			if(eigk[i].first > 0.5 && eigk[i].first < 2){
				cout <<"eigk = " << eig[i].first << endl;
			}

			rsum += eig[i].first;
			ksum += eigk[i].first;

		}

		rsum += eig[rmesh.size()-1].first;

		cout<<"ksum = "<<ksum<<endl;
		cout<<"rsum = "<<rsum<<endl;

		//Transforming natural orbits to k-space
			vector <double> knat;
			knat.assign(kmesh.size(),0);
			for(int ik=0;ik<kmesh.size();ik++){
				double kn=0;
				for(int ir=0;ir<rmesh.size();ir++){
					kn += rdelt_p * sqrt(2.0/M_PI) * bess_mtx(ik,ir) * eig[rmesh.size()-1].second[ir] / rmesh[ir]
					* pow(rmesh_p[ir],2);
				}
				knat[ik] = kn;		
			}
			
		double fnorm=0;
		double fnorm2=0;

		for(int i =0;i<rmesh.size();i++){
			fnorm += pow(knat[i] * kmesh[i],2) * kweights[i];
			fnorm2 += pow(eigk[kmesh.size()-1].second[i] * kmesh[i], 2) * kweights[i];
		}

		cout<<"fnorm = "<<fnorm<<endl;
		cout<<"fnorm2 = "<<fnorm2<<endl;



		string eiglab = dest + "eig" + llab+jlab+".txt";

		ofstream fval(eiglab.c_str());

		matrix_t sky_mtx(Mmax, Mmax); // density matrix
		sky_mtx.clear();


//Starting loop over N
		for(int N=0;N<Nmax;N++){
			string Nlab;
			ostringstream convert;
			convert << N;
			Nlab = convert.str();

			ftable<<Nlab<<"   ";

			double spot = rmesh.size()-N-1;

			double enorm=0;

			for(int i=0;i<rmesh.size();++i){
				enorm += rdelt * pow( eig[spot].second[i],2);
			}

			string veclab = dest + "eig" + llab + jlab + Nlab + ".txt";

			std::ofstream feig(veclab.c_str());

			//opening skyrme file which gives u(r)
			string skyfile0 = presky + llab + jlab + Nlab + ".txt";
			std::ifstream filein0(skyfile0.c_str());
			double sky0[rmesh.size()];
			std::string line0;
			int i;
			i=0;
			while(getline(filein0,line0)){
				sky0[i]=atof(line0.c_str());
				i++;
			}
			filein0.close();

		//flipping the natural orbits if they are upside down
		//	if((eig[spot].second[1]<0 && sky0[1]>0) || (eig[spot].second[1]>0 && sky0[1]<0)){	
			//	for(int i=0;i<rmesh.size();i++){
				//	eig[spot].second[i] *= -1.0;
				//}
			//}

			for(int i=0;i<rmesh.size();++i){
				//want to give R(r), so print out u(r)/r
				feig<<rmesh[i]<<" "<<eig[spot].second[i]/sqrt(enorm)/rmesh[i]<<" "<<sky0[i]/rmesh[i]<<endl;		
			}			

			//Transforming natural orbits to k-space
			vector <double> knat;
			knat.assign(kmesh.size(),0);
			for(int ik=0;ik<kmesh.size();ik++){
				double kn=0;
				for(int ir=0;ir<rmesh.size();ir++){
					kn += rdelt_p * sqrt(2.0/M_PI) * bess_mtx(ik,ir) * eig[spot].second[ir] / sqrt(enorm) / rmesh[ir]
					* pow(rmesh_p[ir],2);
				}
				knat[ik] = kn;		
			}

			double nnorm=0;
			for(int i=0;i<kmesh.size();i++){
				nnorm += pow(knat[i]*kmesh[i],2) * kweights[i];
			}
			
		//	double newnorm=0;

			//for(int i=0;i<kmesh.size();i++){
				//knat[i] /= sqrt(nnorm);
			//	newnorm += pow(knat[i],2);
			//}

			//cout<<"newnorm = "<<nnorm<<endl;

			for(int i=0;i<rmesh.size();i++){
				natden[i] += eig[spot].first*pow(eig[spot].second[i]/rmesh[i]/sqrt(enorm),2)*(2*J+1)/(4*M_PI);
				natdenk[i] += eig[spot].first * pow(knat[i],2) * (2*J+1) / (4*M_PI);
			} 

			vector <double> wave;
			wave.assign(kmesh.size(),0);
			vector <double> waver;
			waver.assign(rmesh.size(),0);
			double csquare=0;

//beginning loop over M to sum over skyrme wave functions
			for(int M=0;M<Mmax;M++){
				string Mlab;
				ostringstream convert;
				convert << M;
				Mlab = convert.str();
				
//opening skyrme file which gives u(r)
				string skyfile = presky + llab + jlab + Mlab + ".txt";
				std::ifstream filein(skyfile.c_str());
				double skyrme[rmesh.size()];
				std::string line;
				int i;
				i=0;
				while(getline(filein,line)){
					skyrme[i]=atof(line.c_str());
					i++;
				}
				filein.close();

		//Transforming skyrme wavefunctions to k-space
				vector <double> ksky;
				ksky.assign(kmesh.size(),0);
				for(int ik=0;ik<kmesh.size();ik++){
					double ks=0;
					for(int ir=0;ir<rmesh.size();ir++){
						ks += rdelt * sqrt(2.0/M_PI) * bess_mtx_sky(ik,ir) * skyrme[ir] * rmesh[ir];
					}
					ksky[ik] = ks;
				}

				if(M==N){
					string test = "waves/neutron/natural/wave" + llab + jlab + Mlab + ".txt";
					ofstream ftest(test.c_str());
					for(int i=0;i<kmesh.size();i++){
						ftest<<kmesh[i]<<" "<<knat[i]<<" "<<ksky[i]<<endl;
					}
				}

				int M2max=Mmax;

				double proj=0;
				for(int i=0;i<kmesh.size();i++){
					proj += ksky[i] * knat[i] * pow(kmesh[i],2) * kweights[i];
				}

				ftable<<proj<<"   ";
		
				for(int M2=0;M2<M2max;M2++){
					string M2lab;
					ostringstream convert;
					convert << M2;
					M2lab = convert.str();

					string skyfile2 = presky + llab + jlab + M2lab + ".txt";
					std::ifstream filein2(skyfile2.c_str());
					double skyrme2[rmesh.size()];
					std::string line2;
					int i;
					i=0;
					while(getline(filein2,line2)){
						skyrme2[i]=atof(line2.c_str());
						i++;
					}
					filein2.close();

					if(N==0){

					//creating matrix in skyrme space
					double sky=0;
					for(int i=0;i<rmesh.size();i++){
						for(int j=0;j<rmesh.size();j++){
							sky += skyrme[i] * skyrme2[j] * d_mtx(i,j) * rdelt;
						}
					}

					sky_mtx(M,M2) = sky;

					}

					//Transforming skyrme wavefunctions to k-space
					vector <double> ksky2;
					ksky2.assign(kmesh.size(),0);
					for(int ik=0;ik<kmesh.size();ik++){
						double ks2=0;
						for(int ir=0;ir<rmesh.size();ir++){
							ks2 += rdelt * sqrt(2.0/M_PI) * bess_mtx_sky(ik,ir) * skyrme2[ir] * rmesh[ir];
						}
						ksky2[ik] = ks2;		
					}

					double proj2=0;
					for(int i=0;i<kmesh.size();i++){
						proj2 += ksky2[i] * knat[i] * pow(kmesh[i],2) * kweights[i];
					}

					//if(M != M2){
						//cout<<"proj1 = "<<proj<<endl;
						//cout<<"proj2 = "<<proj2<<endl;
					//}

					for(int i=0;i<kmesh.size();i++){
						denk[i] += eig[spot].first * (2*J+1) / (4*M_PI) * ksky[i] * ksky2[i] * proj * proj2;
						if(M != M2){
							ktest[i] += eig[spot].first * (2*J+1) / (4*M_PI) * ksky[i] * ksky2[i] * proj * proj2;
						}							
					} 

				} //end loop over M2
				
				for(int i=0;i<kmesh.size();i++){
					wave[i] +=  skyrme[i] * proj;
				}

				csquare += pow(proj,2);

			} //ending loop over M

			ftable<<endl;

		if(L==0){
			dom += eig[spot].first * (2*J+1) / (4*M_PI) * pow(knat[0],2);
			expo += eig[spot].first * (2*J+1) / (4*M_PI) * pow(wave[0],2);
		}

			for(int i=0;i<kmesh.size();i++){
				diag[i] += eig[spot].first * (2*J+1) / (4*M_PI) * pow(wave[i],2);
			}

			double overlap=0;
			for(int i=0;i<kmesh.size();i++){
				overlap += knat[i] * wave[i] * pow(kmesh[i],2) * kweights[i];
			}
			//ut<<" N = "<<N<<" overlap = "<<overlap<<endl;
			//cout<<"N = "<<N<<" csquare = "<<csquare<<endl;

			string comp = "waves/neutron/natural/comp" + llab + jlab + Nlab + ".txt";
			ofstream fcomp(comp.c_str());

			double wavenorm=0;
			double natnorm=0;

			for(int i=0;i<rmesh.size();i++){
				wavenorm += pow(wave[i],2) * rdelt;
			}

			for(int i=0;i<kmesh.size();i++){
				fcomp<<rmesh[i]<<" "<<wave[i]/sqrt(wavenorm)/rmesh[i]<<endl;
			}

		} //ending loop over N
		//ftable.close();

		vector <eigen_t> eigsky = initiate.real_eigvecs(sky_mtx);

		cout<<"Mmax = "<<Mmax<<endl;

		for(int M=0;M<Mmax;M++){
			string Mlab;
			ostringstream convert;
			convert << M;
			Mlab = convert.str();

			int spot = Mmax - M - 1;

			string fname = "waves/eigvec" + llab + jlab + Mlab + ".txt";
			ofstream feigsky(fname.c_str());

			//the eigenvector is already normalized
			for(int i=0;i<Nmax;i++){
				feigsky << eigsky[spot].second[i] << endl;
			}

			cout << "eigval = " << eigsky[spot].first << endl;

			vector<double> qpf;
			qpf.assign(rmesh.size(),0);
		
			for(int j=0;j<Mmax;j++){
		
				string Nlab;
				ostringstream convert;
				convert << j;
				Nlab = convert.str();
				string skyfile = presky + llab + jlab + Nlab + ".txt";
				std::ifstream filein(skyfile.c_str());
				double skyrme[rmesh.size()];
				std::string line;
				int i;
				i=0;
				while(getline(filein,line)){
					skyrme[i]=atof(line.c_str());
					i++;
				}
				filein.close();
				for(int i=0;i<rmesh.size();i++){
					qpf[i] += eigsky[spot].second[j] * skyrme[i];
				}
			}

			string qpname = "waves/nat" + llab + jlab + Mlab + ".txt";
			ofstream qpfile(qpname.c_str());

			double norm=0;

			for(int i=0;i<rmesh.size();i++){
				norm += pow(qpf[i],2) * rdelt;
			}

			double fac;
		
			if(qpf[10] < 0){
				fac = -1.0;
			}else{
				fac = 1.0;
			}


			for(int i=0;i<rmesh.size();i++){
				qpfile << rmesh[i] <<" "<< qpf[i] / sqrt(norm) / rmesh[i] * fac << endl;
			}

		}



	}		//ending loop over j
} 		//ending loop over L

double knum=0;
double kdiag=0;
double kdistnum=0;

ofstream fdiag("waves/neutron/natural/diagk.txt");
ofstream sdenk("waves/neutron/natural/skydenk.txt");
ofstream fdenr("waves/neutron/natural/natden.txt");
ofstream fdenk("waves/neutron/natural/natdenk.txt");
ofstream fdist("waves/kdist.txt");

double k_part=0;
kpart=0;
for(int i=0;i<kmesh.size();i++){
	kpart += denk[i] * pow(kmesh[i],2) * kweights[i] * 4 * M_PI;
	knum += ktest[i] * pow(kmesh[i],2) * kweights[i] * 4 * M_PI;
	k_part += natdenk[i] * kweights[i] * pow(kmesh[i],2) * 4 * M_PI;
	kdiag += diag[i] * kweights[i] * pow(kmesh[i],2) * 4 * M_PI;
	kdistnum += kdist[i] * pow(kmesh[i],2) * kweights[i] * 4 * M_PI;
}

for(int i=0;i<kmesh.size();i++){
	sdenk<<kmesh[i]<<" "<<denk[i]<<endl;
	fdenk<<kmesh[i]<<" "<<natdenk[i]<<endl;
	fdiag<<kmesh[i]<<" "<<diag[i]/kdiag<<endl;
	fdist<<kmesh[i]<<" "<<kdist[i]/kdistnum<<endl;
}

double nat=0;
for(int i=0;i<rmesh.size();i++){
	nat += natden[i] * rdelt_p * pow(rmesh_p[i],2) * 4*M_PI;
}

for(int i=0;i<rmesh.size();i++){
	fdenr<<rmesh_p[i]<<" "<<natden[i]/nat<<endl;
}

cout<<"expoansion = "<<expo/kpart<<endl;
cout<<"natural = "<<dom/k_part<<endl;
cout<<"ktest = "<<knum<<endl;
cout<<"kdiag = "<<kdiag<<endl;
cout<<"particle number from sky density (k) = "<<kpart<<endl;
cout<<"particle number from natural (r) = "<<nat<<endl;
cout<<"particle number from natural (k) = "<<k_part<<endl;
cout<<"particle number from kdist (k) = "<<kdistnum<<endl;

}