Example #1
0
void DrumSet::addDrum()
{
    QFile fin(":/recordnote.txt");
    if (!fin.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QTextStream in(&fin);
    if(!in.atEnd())
    {
        QString line = in.readLine();
        Time = line.toInt();
    }
    if(!in.atEnd())
    {
        QString line = in.readLine();
        DelayTime = line.toInt()-3150;
    }
    while (!in.atEnd())
    {
        QString line = in.readLine();
        QTextStream filein(&line);
        int dr,ti;
        filein>>dr>>ti;
        switch (dr)
        {
            case Qt::Key_I: drum.append(new RedBigDrum(callparent,callparent,RLabel,RMovie)); break;
            case Qt::Key_E: drum.append(new BlueBigDrum(callparent,callparent,LLabel,LMovie)); break;
            case Qt::Key_J: drum.append(new RedSmallDrum(callparent,callparent,RLabel,RMovie)); break;
            case Qt::Key_F: drum.append(new BlueSmallDrum(callparent,callparent,LLabel,LMovie)); break;
        }
        connect(drum[drum.size()-1],SIGNAL(next()),this,SLOT(nextFront()));
        addTimer(ti-11);
    }
}
Example #2
0
int main(int argc, char* argv[]) {

	if (argc != 2) {
		std::cout << "ERROR! The program requires 1 argument, but " << argc - 1 << " were provided." << std::endl;
		std::cout << "Usage: " << argv[0] << " path_to_phrase_table." << std::endl;
	}

	//Read the file
	util::FilePiece filein(argv[1]);

	unsigned long uniq_lines = 0;
	line_text prev_line;

	while (true){
		line_text new_line;
		try {
			//Process line read
			new_line = splitLine(filein.ReadLine());
		} catch (util::EndOfFileException e){
			std::cout << "End of file" << std::endl;
			break;
		}
		if (new_line.source_phrase == prev_line.source_phrase){
			continue;
		} else {
			uniq_lines++;
			prev_line = new_line;
		}
	}

	std::cout << "Number of unique lines is: " << uniq_lines << std::endl;
	return 1;
}
//gets a centroid classifier trained from test data
void LocalDescriptorAndBagOfFeature::load_classifier(std::string filename, std::vector<std::string> &category_labels, std::vector<std::vector<double>> &category_centroids){
    //load codebook from file
    std::ifstream filein (filename);
    std::string s;
    std::getline(filein, s);
    std::istringstream sin(s);

    int category_ct;
    sin >> category_ct;

    for(int i = 0; i < category_ct; i++){
        getline(filein, s);
        category_labels.push_back(s);

        getline(filein, s);
        sin.str(s);
        sin.clear();

        std::vector<double> centroid;
        double d;
        while(sin >> d){
            centroid.push_back(d);
        }
        category_centroids.push_back(centroid);
    }
    filein.close();
}
//read data from file
void UserList::readDatabase()
{
    string infile = "UserDatabase.txt";
    ifstream filein(infile.c_str());
    
    //stores the whole database onto the string
    string allusers;
    filein >> allusers;
    
    //parse for all users
    stringstream stream;
    
    while (!stream.eof())
    {
        string temp;
        User temp2;
        
        //grab a user and calls user class to process it
        getline(stream, temp, '*');
        temp2.readUser(temp);
        
        //stores user onto private linkedlist database
        UserDatabase.set(index, temp2);
        index++;
    }
}
Example #5
0
void CMagicCube3DView::OnOpen()
{	
	CFileDialog fileDlg(true,NULL,NULL,4|2,"MagicCube Layout Files(*.ml)|*.ml||");
	if (fileDlg.DoModal()==IDOK){
		CString filename=fileDlg.GetPathName();
		CFile filein(filename.GetBuffer(),CFile::modeRead);
		filein.Read(((CMagicCube3DApp*)AfxGetApp())->openGL.magicCube.getColorsPtr(),sizeof(Color)*6*9);
		filein.Close();
	}
}
bool VertexBuffer::ReadFromOBJ(string filename)
{
	if (filename.find(".mesh") == string::npos)
		filename.append(".mesh");

	ifstream filein(filename);
	if (!filein)
	{
		string msg("File not found: ");
		msg.append(filename);
		Debug::message(msg);
		return false;
	}

	int vnum;
	vector<TexNormVertex> unique_vertices;

	filein >> vnum;
	unique_vertices.reserve(vnum);

	for (int i = 0; i < vnum; i++)
	{
		float x, y, z, nx, ny, nz;

		filein >> x >> y >> z >> nx >> ny >> nz;

		TexNormVertex v{ { x, y, z }, { nx, ny, nz }, { 0.0f, 0.0f } };

		unique_vertices.push_back(v);
	}

	int inum;
	filein >> inum;
	v_buf.reserve(inum);

	for (int i = 0; i < inum; i++)
	{
		int first, second, third;
		float	first_uv_x, first_uv_y,
			second_uv_x, second_uv_y,
			third_uv_x, third_uv_y;
		filein >> first >> second >> third
			>> first_uv_x >> first_uv_y
			>> second_uv_x >> second_uv_y
			>> third_uv_x >> third_uv_y;

		v_buf.push_back({ unique_vertices[first].pos, unique_vertices[first].normal, { first_uv_x, first_uv_y } });
		v_buf.push_back({ unique_vertices[second].pos, unique_vertices[second].normal, { second_uv_x, second_uv_y } });
		v_buf.push_back({ unique_vertices[third].pos, unique_vertices[third].normal, { third_uv_x, third_uv_y } });
	}

	filein.close();
	return true;
}
Example #7
0
bool CBanDB::Read(banmap_t& banSet)
{
    // open input file, and associate with CAutoFile
    FILE *file = fopen(pathBanlist.string().c_str(), "rb");
    CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
    if (filein.IsNull())
        return error("%s: Failed to open file %s", __func__, pathBanlist.string());

    // use file size to size memory buffer
    uint64_t fileSize = boost::filesystem::file_size(pathBanlist);
    uint64_t dataSize = 0;
    // Don't try to resize to a negative number if file is small
    if (fileSize >= sizeof(uint256))
        dataSize = fileSize - sizeof(uint256);
    std::vector<unsigned char> vchData;
    vchData.resize(dataSize);
    uint256 hashIn;

    // read data and checksum from file
    try {
        filein.read((char *)&vchData[0], dataSize);
        filein >> hashIn;
    }
    catch (const std::exception& e) {
        return error("%s: Deserialize or I/O error - %s", __func__, e.what());
    }
    filein.fclose();

    CDataStream ssBanlist(vchData, SER_DISK, CLIENT_VERSION);

    // verify stored checksum matches input data
    uint256 hashTmp = Hash(ssBanlist.begin(), ssBanlist.end());
    if (hashIn != hashTmp)
        return error("%s: Checksum mismatch, data corrupted", __func__);

    unsigned char pchMsgTmp[4];
    try {
        // de-serialize file header (network specific magic number) and ..
        ssBanlist >> FLATDATA(pchMsgTmp);

        // ... verify the network matches ours
        if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
            return error("%s: Invalid network magic number", __func__);

        // de-serialize ban data
        ssBanlist >> banSet;
    }
    catch (const std::exception& e) {
        return error("%s: Deserialize or I/O error - %s", __func__, e.what());
    }

    return true;
}
Example #8
0
bool CInfiniteMediatorTest::filesEqual(std::string fname0, std::string fname1)
{
  std::ifstream filein(fname0.c_str());
  std::ifstream fileout(fname1.c_str());

  std::istream_iterator<char> end_of_stream;
  std::istream_iterator<char> in_iter(filein);
  std::istream_iterator<char> out_iter(fileout);

  return std::equal(in_iter,end_of_stream,out_iter);

}
Example #9
0
/*
 * read synatag/paradigmatic value from file
 * return map {fromTerm, toTerm, sim}
 * on condition that sim >= threshold
 */
map< string, map<string, double> > readSim(vector<string> &terms, string fin, char fromORto, double threshold, char delim)
{
    // input file
    ifstream filein(fin.c_str());
    if (!filein)
    {
        cout << "Error: can't open " << fin << endl;
        exit (-1);
    }
    if (fromORto!='f' && fromORto!='t')
    {
        cout << "Warning: invalid input in fromORto (f/t)! Use defaulted value f" << endl;
        fromORto = 'f';
    }

    map< string, map<string, double> > synFrom;  // {from, to, syntag}
    map< string, map<string, double> > synTo;    // {to, from, syntag}
    map< string, map<string, double> > score;
    
    // read data from file {from, to syntag}
    string line, fromTerm, toTerm, token;
    double syntag;
    cout << "reading file " << fin << endl;
    while (getline(filein, line))
    {
        stringstream sline(line.c_str());
        getline(sline, fromTerm, delim);
        getline(sline, toTerm, delim);
        getline(sline, token, delim);
        syntag = std::stod(token);
        if (syntag < threshold)
            continue;
        if (fromORto == 'f')
        {
            synFrom[fromTerm][toTerm] = syntag;
            if (find(terms.begin(), terms.end(), fromTerm) == terms.end())
                terms.push_back(fromTerm);
        }
        else
        {
            synTo[toTerm][fromTerm] = syntag;
            if (find(terms.begin(), terms.end(), toTerm) == terms.end())
                terms.push_back(toTerm);
        }
    }
    cout << "loading done!" << endl;
    filein.close();
    if (fromORto == 'f') return synFrom;
    else return synTo;
}
Example #10
0
int main(void) {
    std::vector<std::string> c;
    std::ifstream filein("test.txt");
    std::ofstream fileout("out.txt");
    if(!filein||!fileout) throw std::runtime_error("IO error!");
    std::string s;
    while( filein>>s) {
        c.push_back(s);
    }
    filein.close(); filein.clear();
    for(std::vector<std::string>::iterator i=c.begin(); i!=c.end(); ++i) {
        fileout<<*i<<std::endl;
    }
    fileout.close(); fileout.clear();
    return 0;
}
Example #11
0
/* Function used to get the maximum attribute in both the test file & train file*/
void Adaboost::getMaxAttribute(string file_name){
    /* Read the file */
    ifstream filein(file_name.c_str());
    set<int> attributes;
    if(filein.is_open()) {
        string line;
        while (!filein.eof()){
            getline(filein, line, '\n');
            if(line == "") break;
            istringstream linestr(line);
            string temp;
            while(linestr >> temp){
                /* Get the maximum attribute */
                attributes.insert(atoi(temp.substr(0, temp.find(":")).c_str()));
            }
        }
    }
Example #12
0
int main(int argc, char* argv[])
{
	CxImage image;

    if (argc<3) {
        fprintf(stderr, image.GetVersion());
        fprintf(stderr, "\nConsole demo\n");
        fprintf(stderr, "usage: %s input-file output-file\n", argv[0]);
        return 1;
    }

	CString filein(argv[1]);
	CString extin(FindExtension(filein));
	extin.MakeLower();
	int typein = FindFormat(extin);
	if (typein == CXIMAGE_FORMAT_UNKNOWN) {
        fprintf(stderr, "unknown extension for %s\n", argv[1]);
        return 1;
	}

	CString fileout(argv[2]);
	CString extout(FindExtension(fileout));
	extout.MakeLower();
	int typeout = FindFormat(extout);
	if (typeout == CXIMAGE_FORMAT_UNKNOWN) {
        fprintf(stderr, "unknown extension for %s\n", argv[2]);
        return 1;
	}


	if (!image.Load(argv[1],typein)){
        fprintf(stderr, "%s\n", image.GetLastError());
        fprintf(stderr, "error loading %s\n", argv[1]);
        return 1;
	}

	if (!image.Save(argv[2],typeout)){
        fprintf(stderr, "%s\n", image.GetLastError());
        fprintf(stderr, "error saving %s\n", argv[2]);
        return 1;
	}

	printf("Done!\n");
	return 0;
}
Example #13
0
/*
 * Save an obj file for the set of meshes
 * - outputOBJ: the output filename of the wavefront object file
 * - splitMeshes: will enable exporting meshes as single objects within
 *   the wavefront file
 * - offsetx/y: are global offset, additional to the inner mesh offset
 * - append: option will append meshes to an existing obj file
 *   (filename should be the same)
 */
bool saveOBJ(std::string outputOBJ,
    bool splitMeshes,
    std::vector<std::unique_ptr<PolygonMesh>>& meshes,
    float offsetx,
    float offsety,
    bool append,
    bool normals)
{
    size_t maxindex = 0;

    /// Find max index from previously existing wavefront vertices
    {
        std::ifstream filein(outputOBJ.c_str(), std::ios::in);
        std::string token;

        if (filein.good() && append) {
            // TODO: optimize this
            while (!filein.eof()) {
                filein >> token;
                if (token == "f") {
                    std::string faceLine;
                    getline(filein, faceLine);

                    for (unsigned int i = 0; i < faceLine.length(); ++i) {
                        if (faceLine[i] == '/') {
                            faceLine[i] = ' ';
                        }
                    }

                    std::stringstream ss(faceLine);
                    std::string faceToken;

                    for (int i = 0; i < 6; ++i) {
                        ss >> faceToken;
                        if (faceToken.find_first_not_of("\t\n ") != std::string::npos) {
                            size_t index = atoi(faceToken.c_str());
                            maxindex = index > maxindex ? index : maxindex;
                        }
                    }
                }
            }

            filein.close();
        }
    }
Example #14
0
//#define Multi 1
int main()
{
	CStopWatch sw;
	sw.startTimer();
	std::ofstream fileout("results.txt");
	std::ifstream filein("hands.txt");
	std::string str;
	auto rowCount = 0;

#if Multi
	std::array<std::future<std::string>,MaxThreads-1> futures;
	auto count = 0;
	while (count <MaxThreads-1) {
		if (filein.eof()) break;
		std::getline(filein, str);
		rowCount++;
		//futures[count++] = std::async(ProcessThread, str);
		futures[count++] = std::async([str]{
			PokerHand pokerhand(str);
			auto result = EvaluateHand(pokerhand);
			return pokerhand.GetResult(result);
		});
		if (count == MaxThreads-1) {
			for (auto & e : futures) {
				fileout << e.get() << std::endl;
			}
			count = 0;
		}
	}
#else
	while (std::getline(filein, str))
	{
		PokerHand pokerhand(str);
		auto result = EvaluateHand(pokerhand);
		pokerhand.WriteResult(fileout, result);
		rowCount++;
	}

	#endif	fileout.close();
	filein.close();
	sw.stopTimer();
	std::cout << "Time to evaluate " << rowCount << " poker hands: " << sw.getElapsedTime() << std::endl;
	return 0;
}
void ReadTheory()
{
  ifstream filein("lhc.txt");
  ofstream fileout("lhcM.txt");

  int NN1; 
  double pT[100], y1[100], y2[100], y3[100], y4[100], y5[100], y6[100];

  filein >> NN1;
  for (int i=0; i<NN1; i++) {
    filein >> pT[i] >> y1[i];
    gY1->SetPoint(i, pT[i], y1[i]);
  }

  filein >> NN1;
  for (int i=0; i<NN1; i++) {
    filein >> pT[i] >> y2[i];
    gY2->SetPoint(i, pT[i], y2[i]);
  }

  filein >> NN1;
  for (int i=0; i<NN1; i++) {
    filein >> pT[i] >> y3[i];
    gY3->SetPoint(i, pT[i], y3[i]);
  }

  filein >> NN1;
  for (int i=0; i<NN1; i++) {
    filein >> pT[i] >> y4[i];
    gY4->SetPoint(i, pT[i], y4[i]);
  }

  filein >> NN1;
  for (int i=0; i<NN1; i++) {
    filein >> pT[i] >> y5[i];
    gY5->SetPoint(i, pT[i], y5[i]);
  }

  filein >> NN1;
  for (int i=0; i<NN1; i++) {
    filein >> pT[i] >> y6[i];
    gY6->SetPoint(i, pT[i], y6[i]);
  }
}
Example #16
0
bool read_block(const std::string& filename, CBlock& block)
{
    namespace fs = boost::filesystem;
    fs::path testFile = fs::current_path() / "data" / filename;
#ifdef TEST_DATA_DIR
    if (!fs::exists(testFile))
    {
        testFile = fs::path(BOOST_PP_STRINGIZE(TEST_DATA_DIR)) / filename;
    }
#endif
    FILE* fp = fopen(testFile.string().c_str(), "rb");
    if (!fp) return false;

    fseek(fp, 8, SEEK_SET); // skip msgheader/size

    CAutoFile filein(fp, SER_DISK, CLIENT_VERSION);
    if (filein.IsNull()) return false;

    filein >> block;

    return true;
}
bool read_block(const std::string& filename, cblock& block)
{
    namespace fs = boost::filesystem;
    fs::path testfile = fs::current_path() / "data" / filename;
#ifdef test_data_dir
    if (!fs::exists(testfile))
    {
        testfile = fs::path(boost_pp_stringize(test_data_dir)) / filename;
    }
#endif
    file* fp = fopen(testfile.string().c_str(), "rb");
    if (!fp) return false;

    fseek(fp, 8, seek_set); // skip msgheader/size

    cautofile filein(fp, ser_disk, client_version);
    if (filein.isnull()) return false;

    filein >> block;

    return true;
}
Example #18
0
void
copyin(register Archive_t* ap)
{
	register File_t*	f = &ap->file;

	deltabase(ap);
	while (getprologue(ap))
	{
		while (getheader(ap, f))
		{
			if (selectfile(ap, f))
				filein(ap, f);
			else
				fileskip(ap, f);
			if (ap->info)
				ap->info->checksum = ap->memsum;
			gettrailer(ap, f);
		}
		if (!getepilogue(ap))
			break;
	}
	deltaverify(ap);
}
int main(int argc, char const *argv[])
{
	std::stringstream output_filename;
	output_filename << argv[1];
	output_filename << ".ineV";
	std::ofstream fileout (output_filename.str().c_str(), std::ofstream::out);

	std::ifstream filein (argv[1], std::ifstream::in);
	agn::sed_table output_table = agn::read_and_convert_sed_table(filein);

    std::cout << "Found " 
    			<< output_table.value.size()
    			<< " photon indices with "
    			;
    if (output_table.header.empty()) std::cout << "no file header.";
    else  std::cout << "a file header.";
    std::cout << "\n";

	// Write to new file
    fileout << agn::format_sed_table(output_table);

	return 0;
}
Example #20
0
bool CAddrDB::Read(CAddrMan& addr)
{
    // open input file, and associate with CAutoFile
    FILE *file = fopen(pathAddr.string().c_str(), "rb");
    CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
    if (filein.IsNull())
        return error("%s: Failed to open file %s", __func__, pathAddr.string());

    // use file size to size memory buffer
    uint64_t fileSize = boost::filesystem::file_size(pathAddr);
    uint64_t dataSize = 0;
    // Don't try to resize to a negative number if file is small
    if (fileSize >= sizeof(uint256))
        dataSize = fileSize - sizeof(uint256);
    std::vector<unsigned char> vchData;
    vchData.resize(dataSize);
    uint256 hashIn;

    // read data and checksum from file
    try {
        filein.read((char *)&vchData[0], dataSize);
        filein >> hashIn;
    }
    catch (const std::exception& e) {
        return error("%s: Deserialize or I/O error - %s", __func__, e.what());
    }
    filein.fclose();

    CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);

    // verify stored checksum matches input data
    uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
    if (hashIn != hashTmp)
        return error("%s: Checksum mismatch, data corrupted", __func__);

    return Read(addr, ssPeers);
}
	bool LoadMyFormatModel(const char* filename, 
						float scale,
						Vector3f **vertexData, 
						Vector3f **normalData, 
						Vector3f **binormalData, 
						Vector3f **tangentData, 
						Vector3f **texCoords, 				
						unsigned int **indexData,
						unsigned int &numOfIndices,
						unsigned int &numOfVertices)
	{
		std::ifstream filein(filename);
		if (!filein)
			return false;
		std::string name;
		unsigned int vertexCount = 0;
		unsigned int indexSize = 0;
		filein >> name;
		filein >> name;
		if (name.compare("arraysize") == 0)
		{
			filein >> vertexCount;
			filein >> indexSize;
		}
Example #22
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/pca40.inp" );

double Ef=Nu.Ef;
int lmax=5;
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;
double  rStart = .05;
double  rmax = 12.;
double  ham_pts = 180; 

double  rdelt = rmax / ham_pts;

        // 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///

// std::vector<double> rmesh_p= initiate.make_rmesh_point();
 std::vector<double> rmesh_p= initiate.make_rmesh_point();
 std::vector<double> rmesh= initiate.make_rmesh();


////////////////////////////
//// s and d wave functions////
///////////////////////////
int N = 0;
int L = 1;
double J = 0.5;

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

eigen_t waves0=initiate.find_boundstate(rmesh_p, estart,0,L,J,tol);
eigen_t waves1=initiate.find_boundstate(rmesh_p, estart,1,L,J,tol);
eigen_t waves2=initiate.find_boundstate(rmesh_p, estart,2,L,J,tol);
eigen_t waves3=initiate.find_boundstate(rmesh_p, estart,3,L,J,tol);
eigen_t waves4=initiate.find_boundstate(rmesh_p, estart,4,L,J,tol);
eigen_t waves5=initiate.find_boundstate(rmesh_p, estart,5,L,J,tol);
eigen_t waves6=initiate.find_boundstate(rmesh_p, estart,6,0,0.5,tol);

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

// Plottinge Pot and wavefuntionsa and their log//
// and also the derivitaves
//////////////////////
double norm0=0,norm1=0,norm2=0,norm3=0,norm4=0,norm5=0,norm6=0;
double normAsymp_s = 0.;
double normAsymp_d = 0.;
double Mproton = 931.5;// 937.27;
double normbob= 0.;

//double Ed = -waves_d.first;
//double Es = -waves_s.first;
//double bbetta_d = std::sqrt(2. * Mproton * (40./41.) * Ed /(197. * 197.));
//double bbetta_s = std::sqrt(2. * Mproton * (40./41.) * Es /(197. * 197.));
//double llambbda = 2.0 * Mproton * (40./41.) * 1.44 * 19. /(197. * 197.);

for(int ii=0;ii<rmesh_p.size();++ii){
      norm0 += rdelt * std::pow(rmesh_p[ii] * waves0.second[ii],2) ;
			norm1 += rdelt * std::pow(rmesh_p[ii] * waves1.second[ii],2) ;
			norm2 += rdelt * std::pow(rmesh_p[ii] * waves2.second[ii],2) ;
			norm3 += rdelt * std::pow(rmesh_p[ii] * waves3.second[ii],2) ;
			norm4 += rdelt * std::pow(rmesh_p[ii] * waves4.second[ii],2) ;
			norm5 += rdelt * std::pow(rmesh_p[ii] * waves5.second[ii],2) ;
			norm6 += rdelt * std::pow(rmesh_p[ii] * waves6.second[ii],2) ;
      //normAsymp_s += rdelt * std::pow((exp(-bbetta_s * rmesh_p[ii]) * std::pow(rmesh_p[ii], -llambbda /( 2.0 * bbetta_s))) ,2); 
      //normAsymp_d += rdelt * std::pow((exp(-bbetta_d * rmesh_p[ii]) * std::pow(rmesh_p[ii], -llambbda /( 2.0 * bbetta_d))) ,2); 
      //normbob += rdelt * std::pow(rmesh_p[ii] * initiate.WaveArray[ii],2);
}


/////////////////////// ADDING CODE FOR SPECTRAL FUNCTION FOLDING WITH SKYRME ////////////////////////

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

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 );

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

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

std::vector< double > bspec = initiate.spectral_strength( L, J, rmesh, emesh_vec, prop_vec );

mesh_t energym = initiate.get_lj_emesh(L,J,emesh_vec ); 

eigen_t bound_info = initiate.find_boundstate( rmesh, estart, N, L, J, tol );

std::vector< double > &QPF = bound_info.second;

double QPE = bound_info.first;

double S = initiate.sfactor( rmesh, QPE, L, J, QPF );

std::vector< double > chd = initiate.charge_density(rmesh, Emax, emesh_vec, prop_vec, bound_levels);

vector <double> pdist = initiate.point_distribution(rmesh_p,Emax,emesh_vec,prop_vec,bound_levels);

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

//making it so that wavefunction takes skyrme wavefunction as the input and finds the skyrme spectral function

std::ifstream filein("waves/upp12.txt");

double skyrme[rmesh.size()];

std::string line;

double part=0;
double part2=0;

for(int i=0;i<rmesh.size();i++){
	part += chd[i] * rdelt * pow(rmesh[i],2) * 4 * M_PI;
	part2 += pdist[i] * rdelt * pow(rmesh[i],2) * 4 * M_PI;
}

cout<<"Particle Number = "<<part<<endl;
cout<<"Particle Number2 = "<<part2<<endl;

int iii;
iii=0;
while(getline(filein,line)){
	skyrme[iii]=atof(line.c_str());
	iii++;
}

filein.close();

int esize;
esize=emesh.size();

std::vector<double> spec;
std::vector<double> spec2;

std::vector <double> dom0,dom1,dom2,dom3,dom4,dom5,dom6;
double dwave0,dwave1,dwave2,dwave3,dwave4,dwave5,dwave6;

for(int i=0;i<rmesh.size();i++){
	dwave0=rmesh[i]*waves0.second[i]/norm0;
	dom0.push_back(dwave0);
	dwave1=rmesh[i]*waves1.second[i]/norm1;
	dom1.push_back(dwave1);
	dwave2=rmesh[i]*waves2.second[i]/norm2;
	dom2.push_back(dwave2);
	dwave3=rmesh[i]*waves3.second[i]/norm3;
	dom3.push_back(dwave3);
	dwave4=rmesh[i]*waves4.second[i]/norm4;
	dom4.push_back(dwave4);
	dwave5=rmesh[i]*waves5.second[i]/norm5;
	dom5.push_back(dwave5);
	dwave6=rmesh[i]*waves6.second[i]/norm6;
	dom6.push_back(dwave6);
}


//Remember that propE is actually G*r*r'*rdelt
for(unsigned int n=0;n<emesh.size();++n){
	double spf=0.0;
	double spf2=0.0;
	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 * rmesh[i] * rmesh[j] * rdelt);
			d_mtx(i,j) += Edelt * imag(propE[n](i,j)) / M_PI; 
  		spf -= rdelt * skyrme[i] * skyrme[j] *imag( propE[n]( i, j ) ) / M_PI;
			spf2 -= rdelt * dom0[i]*dom0[j] *imag( propE[n]( i, j ) ) / M_PI;
			//spf -= rmesh[i] * rmesh[j] * rdelt / M_PI
      //            * QPF[i] * QPF[j] * imag( propE[n]( i, j ) );
  	} 
	} 
	spec.push_back(spf);
	spec2.push_back(spf2);
}

std::ofstream fmtx("waves/dmtx.txt");

for(int i=0;i<rmesh.size();i++){
	for(int j=0;j<rmesh.size();j++){
		fmtx<<d_mtx(i,j)<<" ";
	}
	fmtx<<endl;
}

fmtx.close();
		

std::vector <eigen_t> eig = initiate.real_eigvecs(d_mtx);

double norme=0.0;
double norm=0.0;
double eigsum=0.0;
double maxeig=0.0;

norm0=0,norm1=0,norm2=0,norm3=0,norm4=0,norm5=0,norm6=0;

for(int i=0;i<rmesh.size();++i){
	norm0 += rdelt * pow( eig[0].second[i],2);
	norm1 += rdelt * pow( eig[1].second[i],2);
	norm2 += rdelt * pow( eig[2].second[i],2);
	norm3 += rdelt * pow( eig[3].second[i],2);
	norm4 += rdelt * pow( eig[4].second[i],2);
}

double occ=0.0;

for (int i=0;i<rmesh.size();++i){
	for (int j=0;j<rmesh.size();++j){
		occ += rdelt*rdelt * d_mtx(i,j) * eig[N].second[i]/std::sqrt(norm) * eig[N].second[j]/std::sqrt(norm) * pow(rmesh[i],2) * pow(rmesh[j],2);
	}
}

//cout<<"QP OCCUPATION NUMBER = "<<initiate.occupation(rmesh,d_mtx,QPF)<<endl;

//cout<<"occupation number = "<<occ<<endl;

ofstream fval("waves/i13 2.txt");

fval<<eig[0].first*-1<<std::endl;
fval<<eig[1].first*-1<<std::endl;
fval<<eig[2].first*-1<<endl;
fval<<eig[3].first*-1<<endl;
fval<<eig[4].first*-1<<endl;



std::ofstream feig("waves/eig.out");

//std::cout<<"Here is an eigenvector"<<std::endl;
double esum=0.0;
for(int i=0;i<rmesh.size();++i){
	//want to give R(r), so print out u(r)/r
	feig<<rmesh[i]<<" "<<eig[0].second[i]/sqrt(norm0)/rmesh[i];
	feig<<" "<<eig[1].second[i]/sqrt(norm1)/rmesh[i];
	feig<<" "<<eig[2].second[i]/sqrt(norm2)/rmesh[i];
	feig<<" "<<eig[3].second[i]/sqrt(norm3)/rmesh[i];
	feig<<" "<<eig[4].second[i]/sqrt(norm4)/rmesh[i]<<endl;;
//	esum += rdelt*pow(rmesh[i]*eig[N].second[i]/sqrt(norme),2);
}

//std::cout<<"esum = "<<esum<<std::endl;

//This is where I will find rhobar, ask houssein how to put in clebsch gordon and spherical harmonics
double dens=0.0;
int nt=50;
int np=25;
double dt=2*M_PI/nt;
double dp=M_PI/np;
for(int i=0;i<rmesh.size();i++){
	for(int j=0;j<nt;j++){
		for(int k=0;k<np;k++){
			dens+= rdelt*rdelt * skyrme[i]*skyrme[i] * chd[i]; //* spherical harmonics and clebsch gordon * sin(theta)
		}
	}
}

std::vector< double >  s_of_Eqh = initiate.spectral_strength_QH( L, J, rmesh, emesh_vec, prop_vec, QPF);

std::ofstream fden("waves/chd.out");
ofstream fpoint("waves/p.out");
std::ofstream fileout("waves/spec.out");
std::ofstream files("waves/skyrme.out");
std::ofstream fileq("waves/quasi.out");
std::ofstream filef("waves/fold.out");
std::ofstream filed("waves/dom.out");
std::ofstream filer("waves/r.out");
//std::ofstream filep("waves/prop.out");

for(int i=0;i<rmesh.size();i++){
	files<<skyrme[i]<<endl;
	fileq<<QPF[i]<<endl;
	filer<<rmesh[i]<<" "<<rmesh_p[i]<<endl;
	fden<<rmesh[i]<<" "<<chd[i]<<endl;
	fpoint<<rmesh[i]<<" "<<pdist[i]<<endl;
}

for(int i=0;i<bspec.size();i++){
	fileout<<energym[i].first<<" "<<energym[i].second<<" "<<spec[i]<<endl;
	filed<<energym[i].first<<" "<<energym[i].second<<" "<<spec2[i]<<endl;
	filef<<energym[i].first<<" "<<energym[i].second<<" "<<s_of_Eqh[i]<<endl;	
}

filed.close();
filer.close();
filef.close();
fileq.close();
files.close();
fileout.close();

///////////  END OF ADDED CODE ///////////////////////////////////////



////////
//normalizing wavefunctions at 4.008 to s wave to compare the asymptotic behaviour and energy
//the value of s at 4.008 is .023309//d is .132997 , s_asymp is .000271922 , d_asymp  i s .000336918
/////////
for(int ii=0;ii<rmesh.size();++ii){
      filee<<dom0[ii]/rmesh[ii]<<" "<<dom1[ii]<<" "<<dom2[ii]<<" "<<dom3[ii]<<" "<<dom4[ii]<<" "<<dom5[ii]<<std::endl;  
}
//std::cout <<"Es =" << waves_s.first << " " << "Ed= " << waves_d.first <<std::endl;
//std::cout << zp0 << " " << tz<<" "<<norm_s<<" "<< norm_d<<" "<< normAsymp_s<<" norm bob=" << normbob<< std::endl;
//std::cout <<"Elower = "<< Elower <<" " << "Eupper = " << Eupper<<std::endl;
filee.close();
std::cout<<"Spectral Factor = "<<S<<endl;
std::cout<<"Quasi-hole Energy = "<<QPE<<endl;
return 0;

}
Example #23
0
void dileptonMassFit(const char* pInFileName="PanchoSkim4JanAll.root",
                     // "PromtRecoV2V3V3H_DiMuonPlot_TightSTACutsAll15Dec.root",
                     // "Z0_DataMixPt50_PatDiMuonPlots_NewCutAll14Dec.root",
                     const char* pHistNameOpCh="diMuonsGlobalInvMassVsPt",//diMuonsGlobalInvMassVsPtW",
                     const char* pHistNameSameCh="diMuonsGlobalSameChargeInvMassVsPt",
                     const char* pSpectra="pt",  // pt, y, centr
                     bool doMc=false,
                     int nFitFunction = 3,
                     int getYield = 1)
{
    gROOT->Macro("setStyle.C+");

    //gROOT->Macro("/Users/eusmartass/Software/utilities/setStyle.C+");
    char szBuf[256];

    ////////  definitions of Switches   ///////////
    //  nFitFunction  = 1  RBW + Pol2
    //  nFitFunction  = 2  Gaus + Pol2
    //  nFitFunction  = 3  RBWGaus + Pol2

    //  getYield = 1  Bin counting
    //  getYield = 2  Integral
    ////////////////////////////////////////////////////////////

    // make some choices
    float MassZ0         = 91.1876;
    float WidthZ0        = 2.4952;
    float massFit_low    = 60;
    float massFit_high   = 120;   // Fit ranges
    float massDraw_low   = 30.0;  // 0.
    float massDraw_high  = 130.0; // 200/
    int nrebin           = 80;
    bool isLog           = 0;
    bool isFit           = 1; // draw ranges

    float massCount_low  = 60.0; //78.0
    float massCount_high = 120.0; //102.0

    //___________________________________________________________________________________
    // ------- Open input file
    sprintf(szBuf,"%s",pInFileName);
    TString inFileName(szBuf);
    TFile *pfInFile = new TFile(inFileName);

    // ------- get histograms:
    sprintf(szBuf,"%s",pHistNameOpCh);
    TH2D *phDimuMass_1  = (TH2D*)pfInFile->Get(szBuf)->Clone("phDimuMass_1");

    sprintf(szBuf,"%s",pHistNameSameCh);
    TH2D *phDimuMass_1S = (TH2D*)pfInFile->Get(szBuf)->Clone("phDimuMass_1S");

    phDimuMass_1->SetDirectory(0);
    phDimuMass_1S->SetDirectory(0);

    // Open pp data file

    TFile *ppFile = new TFile("Zmumu_40-200_35pb.root");
    TH1F *Zmumu  = (TH1F*)ppFile->Get("hdata");


    //___________________________________________________________________________________
    // bins definition:
    const char* Xname[] = {" ", "p_{T}^{Dimuon} (GeV/c)", "rapidity", "centrality"};
    bool doPt   = false;
    bool doY    =  false;
    bool doCent = false;

    int GenRange, nBins;
    double binEdge[10];
    char* label;
    sprintf(szBuf,"%s",pSpectra);
    TString wichSpectra(szBuf);

    if ( wichSpectra.CompareTo("pt") == 0) {
        doPt               = true;
        label              = (char*)Xname[1];
        GenRange           = 20;
        nBins              = 1;
        binEdge[0] = 0.0;
        binEdge[1]= 100.0;
        //    double binEdge[10] = {0.0, 10., 20., 100.0};
        if(doMc) {
            nBins              = 1;
            binEdge[0] = 0.0;
            binEdge[1]= 50.0;
            //	  nBins          = 7;
            // binEdge[0] =  0.0;  binEdge[1] =  2.0;  binEdge[2] =  4.0;  binEdge[3] = 8.0;
            //binEdge[4] = 12.0;  binEdge[5] = 16.0;  binEdge[6] = 22.0;  binEdge[7] = 50.0;
        }
    } else {
        if ( wichSpectra.CompareTo("y") == 0) {
            doY              = true;
            label            = (char*)Xname[2];
            nBins            = 3;
            GenRange         = 4.8;
            binEdge[0] = -2.4;
            binEdge[1] = -0.8;
            binEdge[2] =  0.8;
            binEdge[3] =  2.4;
        } else {
            if ( wichSpectra.CompareTo("cent") == 0) 	{
                doCent           = true;
                label            = (char*)Xname[3];
                nBins            = 4;
                GenRange         = 40;
                binEdge[0] = 0.;
                binEdge[1] =   4;
                binEdge[2] = 8.;
                binEdge[3] =  16;
                binEdge[4] =  40;
            } else {
                cout<<"Don't know what you want to do!!!!"<<endl;
                return;
            }
        }
    }

    double PT[10], DelPT[10], mom_err[100];
    for (Int_t ih = 0; ih < nBins; ih++)  {
        PT[ih]      = (binEdge[ih] + binEdge[ih+1])/2.0;
        DelPT[ih]   = binEdge[ih+1] - binEdge[ih];
        mom_err[ih] = DelPT[ih]/2.0;
    }

    //___________________________________________________________________________________

    double gen_pt[10];
    double egen_pt[10];

    TCanvas *pcPt_1 = new TCanvas("pcPt_1"," Z0 Yield Vs. Pt ", 40,40,600,600);

    if(doMc) {
        pcPt_1->Divide(nBins,2);

        //TH2D *genMass_1 = (TH2D*)pfInFile->Get("diMuonsGenInvMassVsPt");
        TH2D *genMass_1 = (TH2D*)pfInFile->Get("diMuonsGenInvMassVsPtW");
        TH1D *ptaxis    = (TH1D*)genMass_1->ProjectionY("ptaxis");

        for (Int_t ih = 0; ih < nBins; ih++) {
            pcPt_1->cd(ih+nBins+1);

            int bin1 = ptaxis->FindBin(binEdge[ih]+0.0000001);
            int bin2 = ptaxis->FindBin(binEdge[ih+1]+0.0000001);

            TH1D * genMassVsPt = (TH1D*)genMass_1->ProjectionX("genMassVsPt", bin1, bin2-1);
            genMassVsPt->Draw("EPL");
            pcPt_1->Update();

            TAxis *axs        = genMassVsPt->GetXaxis();
            int binlow        = axs->FindBin(massCount_low);
            int binhi         = axs->FindBin(massCount_high);

            double int_sig_gen;
            double int_sig_gen_sqr;
            for(Int_t bin = binlow; bin<=binhi; bin++) {
                //    cout << "	  int_sig += dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin);"<<int_sigpow_gen <<"+="<< "bin" << bin << " content"<<genMassVsPt->GetBinContent(bin)<<endl;
                int_sig_gen += genMassVsPt->GetBinContent(bin);
                int_sig_gen_sqr += pow(genMassVsPt->GetBinContent(bin),2);
            }


            gen_pt[ih] = int_sig_gen;//genMassVsPt->GetEntries();
            cout<<" gen entries : "<< gen_pt[ih]<<endl;
            egen_pt[ih] =int_sig_gen_sqr;

        }
    }
    else {
        if (nBins == 2)  pcPt_1->Divide(2,1);
        if (nBins == 3 || nBins == 4)  pcPt_1->Divide(2,2);
        if (nBins == 5 || nBins == 6)  pcPt_1->Divide(3,2);

    }


    //___________________________________________________________________________________
    // Fit Function
    //  const char *name_fit[] = {"  ", "RBWPol1", "GausPol1", "RBWGausPol2"};
    int nParam[]           = {0,6,6,7};
    int nFitParam          = nParam[nFitFunction];
    TF1 *RBWPOL=0;
    if(nFitFunction == 1) RBWPOL = new TF1("RBWPOL", RBWPol2,     0, 200, nFitParam);
    if(nFitFunction == 2) RBWPOL = new TF1("RBWPOL", GausPol2,    0, 200, nFitParam);
    if(nFitFunction == 3) RBWPOL = new TF1("RBWPOL", RBWGausPol2, 0, 200, nFitParam);
    TF1 *EXP               = new TF1("EXP", Exp, 0, 200, 2);

    RBWPOL->SetLineWidth(1);
    RBWPOL->SetParameter(1, MassZ0);
    RBWPOL->SetParameter(2, WidthZ0);

    RBWPOL->SetParLimits(1, 0.9*MassZ0, 1.1*MassZ0);
    RBWPOL->SetParLimits(2, 0.1*WidthZ0, 5.0*WidthZ0);

    if(nFitFunction  == 1 || nFitFunction  == 2) RBWPOL->FixParameter(5, 0);
    if(nFitFunction  == 3 || nFitFunction  == 4)  {
        RBWPOL->SetParameter(3, WidthZ0);
        RBWPOL->SetParLimits(3, 0.1, 20);
        RBWPOL->FixParameter(2, WidthZ0);

        RBWPOL->FixParameter(4, 0);   // for no bkg
        RBWPOL->FixParameter(5, 0);   // for no bkg
        RBWPOL->FixParameter(6, 0);
    }


    //___________________________________________________________________________________
    // Efficiency

    double yld_cat_1[10], cyld_cat_1[10], eyld_cat_1[10], ceyld_cat_1[10];
    double Eff_cat_1[10], errEff_cat_1[10];


    ///// Write the spectra
    sprintf(szBuf,"fileSpecta%d.root", getYield);
    //  TFile *fileSpectra = new TFile(szBuf, "recreate");


    //___________________________________________________________________________________
    // Drawing
    // Category _1
    TLegend *pLegCategory = new TLegend(.66, .74, .92, .94);
    //  pLegCategory = new TLegend(.1, .82, .50, .93);
    pLegCategory->SetBorderSize(0);
    pLegCategory->SetFillStyle(0);
    pLegCategory->SetFillColor(0);
    pLegCategory->SetTextSize(0.03);
    //  pLegCategory->AddEntry(RBWPOL," CMS Preliminary", " ");

    pLegCategory->AddEntry(RBWPOL," CMS Pb+Pb ", " ");
    pLegCategory->AddEntry(RBWPOL," #sqrt{s_{NN}} = 2.76 TeV ", " ");
    pLegCategory->AddEntry(RBWPOL," #int Ldt  = 6.6 #mub^{-1} ", " ");

    //  pLegCategory->AddEntry(RBWPOL," Global-Global ", "");
    //pLegCategory->AddEntry(RBWPOL," |y| < 2.4 ", "P");
    //pLegCategory->AddEntry(RBWPOL," Run# 150431-151027 ", "P");

    TLegend *legend_1[12];
    for(int i=0; i<12; i++) {
        if(isFit) legend_1[i] = new TLegend(.13, .66, .52, 0.94);
        if(!isFit) legend_1[i] = new TLegend(.13, .66, .52, 0.94 );
        //    legend_1[i] = new TLegend(.68, .62, .91, 0.93 );
        legend_1[i]->SetBorderSize(0);
        legend_1[i]->SetFillStyle(0);
        legend_1[i]->SetFillColor(0);
        legend_1[i]->SetTextSize(0.028);
    }

    int bin_bound[100];
    TH1D *dimuonsGlobalInvMassVsPt[10];
    TH1D *dimuonsGlobalInvMassVsPtS[10];
    TH1D *service = (TH1D*)phDimuMass_1->ProjectionY("service");

    //  cout << endl << label << "    Yield      Mass (GeV)    Width (GeV)    GauWidth    chi2/ndf " << endl << endl;
    for (Int_t ih = 0; ih < nBins; ih++)  {
        pcPt_1->cd(ih+1);
        gPad->SetTickx();
        gPad->SetTicky();

        // Project 1 D
        bin_bound[ih]   = service->FindBin(binEdge[ih]+0.0000001);
        bin_bound[ih+1] = service->FindBin(binEdge[ih+1]+0.0000001);

        sprintf(szBuf,"Z0_1_pt_%d",ih);
        dimuonsGlobalInvMassVsPt[ih]  = (TH1D*)phDimuMass_1->ProjectionX(szBuf, bin_bound[ih], bin_bound[ih+1]-1+1, "e");
        sprintf(szBuf,"Z0_1S_pt_%d",ih);
        dimuonsGlobalInvMassVsPtS[ih] = (TH1D*)phDimuMass_1S->ProjectionX(szBuf, bin_bound[ih], bin_bound[ih+1]-1+1);
        cout << "reco entries" << dimuonsGlobalInvMassVsPt[ih]->GetEntries() <<endl;
        if(doPt || doY) {
            sprintf(szBuf," %s [%.1f, %.1f]",
                    label,
                    service->GetBinLowEdge(bin_bound[ih]),
                    service->GetBinLowEdge(bin_bound[ih+1]-1) + service->GetBinWidth(bin_bound[ih+1]));
        }

        if(doCent) {
            sprintf(szBuf," %s [%.1f, %.1f] %s",
                    label,
                    2.5*service->GetBinLowEdge(bin_bound[ih]),
                    2.5*(service->GetBinLowEdge(bin_bound[ih+1]-1) + service->GetBinWidth(bin_bound[ih+1])), "%");
        }

        dimuonsGlobalInvMassVsPt[ih]->Rebin(nrebin);
        dimuonsGlobalInvMassVsPtS[ih]->Rebin(nrebin);

        // -------- Fit Function + Bkg Function
        double part[20];
        dimuonsGlobalInvMassVsPt[ih]->Fit("EXP","LEQ", "", 34, 60);
        EXP->GetParameters(part);
        if(nFitFunction  == 4) {
            RBWPOL->FixParameter(4, part[0]);
            RBWPOL->FixParameter(5, part[1]);
        }

        if(isFit) {
            //dimuonsGlobalInvMassVsPt[ih]->Fit("RBWPOL","LEQ", "", massFit_low, massFit_high);
            //TFitResultPtr r =
            dimuonsGlobalInvMassVsPt[ih]->Fit("RBWPOL","LEQS0","", massFit_low, massFit_high);
            //	if(r->IsValid()) r->Print();
            //else cout<<"Fit not valid!!!\n"<<endl;
        }

        //------  get fit parameters
        double par[20];
        RBWPOL->GetParameters(par);

        float GGphDimuMass = RBWPOL->GetParameter(1);
        float GGZ0Width    = RBWPOL->GetParameter(2);
        float GauWidth     =0;
        if(nFitFunction  == 3 || nFitFunction  == 4) GauWidth = RBWPOL->GetParameter(3);

        double chisq      = RBWPOL->GetChisquare();
        int ndf           = RBWPOL->GetNDF();
        double chisqdf    =1000;
        if(ndf!=0) chisqdf=chisq/ndf;

        // +++ set backgroudn fit
        sprintf(szBuf,"pt_1B_%d",ih);
        TF1 *bkgFit_1 = new TF1(szBuf, Pol2, massFit_low, massFit_high, 3);
        // if(nFitFunction  == 4) bkgFit_1 = new TF1(namePt_1B, Exp, massFit_low, massFit_high, 2);

        bkgFit_1->SetParameters(&par[3]);
        if(nFitFunction  == 3 || nFitFunction  == 4) bkgFit_1->SetParameters(&par[4]);

        // ----------  Integrated Yield
        //    float massCount_low =GGphDimuMass-(4.0*GGZ0Width);
        //    float massCount_high =GGphDimuMass+(4.0*GGZ0Width);

        TAxis *axs        = dimuonsGlobalInvMassVsPt[ih]->GetXaxis();
        int binlow        = axs->FindBin(massCount_low);
        int binhi         = axs->FindBin(massCount_high);
        Double_t bin_size = (1.0*dimuonsGlobalInvMassVsPt[ih]->GetNbinsX())/(axs->GetXmax() - axs->GetXmin());

        Float_t int_sig   = 0.0;
        Float_t int_sig_sqr   = 0.0;
        for(Int_t bin = binlow; bin<=binhi; bin++) {
            //	  cout << "	  int_sig += dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin);"<<int_sig <<"+="<< "bin" << bin << " content"<<dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin)<<endl;
            int_sig += dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin);
            int_sig_sqr += pow(dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin),2);
        }

        if(getYield == 2) {
            int_sig =  RBWPOL->Integral(massCount_low, massCount_high)*bin_size;
            yld_cat_1[ih]   = int_sig - bin_size*bkgFit_1->Integral(massCount_low, massCount_high);
            eyld_cat_1[ih] = TMath::Sqrt(int_sig + bin_size*bkgFit_1->Integral(massCount_low, massCount_high) );
        }

        else {
            yld_cat_1[ih]   = int_sig ;
            eyld_cat_1[ih] = int_sig_sqr;
        }
        cout << "int_sig - bin_size*bkgFit_1->Integral(massCount_low, massCount_high);" << int_sig<< "  -"<< bin_size<<"*"<<bkgFit_1->Integral(massCount_low, massCount_high)<< " with low"<< massCount_low<<" high "<< massCount_high<<endl;
        //// Printing /////
        cout <<  PT[ih] << "    " << yld_cat_1[ih] << " +- " << eyld_cat_1[ih] <<"     " << GGphDimuMass << "    " << GGZ0Width  << "    " << GauWidth <<"   "<< chisq << "/" << ndf  << endl;


        // -------------- Draw
        //    dimuonsGlobalInvMassVsPt[ih]->SetMinimum(-.05*dimuonsGlobalInvMassVsPt[ih]->GetMaximum());

        if(isLog) gPad->SetLogy(1);

        TColor *pal    = new TColor();
        Int_t kblue    = pal->GetColor(9,0,200);
        //    Int_t korange  = pal->GetColor(101, 42,  0);

        // +++ opposite charge
        dimuonsGlobalInvMassVsPt[ih]->SetMarkerStyle(21);
        dimuonsGlobalInvMassVsPt[ih]->SetMarkerColor(kblue);
        dimuonsGlobalInvMassVsPt[ih]->SetLineColor(kblue);
        dimuonsGlobalInvMassVsPt[ih]->SetMarkerSize(1.1);
        dimuonsGlobalInvMassVsPt[ih]->GetXaxis()->SetTitle("Dimuon mass (GeV/c^{2})");
        dimuonsGlobalInvMassVsPt[ih]->GetYaxis()->SetTitle("dN/dM (2 GeV/c^{2})^{-1}");

        dimuonsGlobalInvMassVsPt[ih]->GetXaxis()->SetRangeUser(massDraw_low,massDraw_high);
        //    dimuonsGlobalInvMassVsPt[ih]->Add(dimuonsGlobalInvMassVsPtS[ih], -1);

        pcPt_1->cd(ih+1);


        dimuonsGlobalInvMassVsPt[ih]->DrawCopy("EPLsame");

        // pp data

        TAxis *axs1   = Zmumu->GetXaxis();
        int ll        = axs1->FindBin(massCount_low);
        int hh        = axs1->FindBin(massCount_high);

        double scalefactor =  yld_cat_1[ih]/Zmumu->Integral(ll, hh);

        cout << Zmumu->Integral(ll, hh) << endl;

        Zmumu->Scale(scalefactor);

        Zmumu->SetFillColor(19);

        Zmumu->Draw("same");

        dimuonsGlobalInvMassVsPt[ih]->DrawCopy("EPLsame");

        //    dimuonsGlobalInvMassVsPt[ih]->Draw("B");

        // +++ same charge
        dimuonsGlobalInvMassVsPtS[ih]->SetMarkerStyle(8);
        dimuonsGlobalInvMassVsPtS[ih]->SetMarkerColor(46);
        dimuonsGlobalInvMassVsPtS[ih]->SetLineColor(46);

        dimuonsGlobalInvMassVsPtS[ih]->SetMarkerSize(1.1);
        dimuonsGlobalInvMassVsPtS[ih]->DrawCopy("EPsame");


        // background
        //    RBWPOL->SetLineColor(kblue);
        bkgFit_1->SetLineColor(46);
        bkgFit_1->SetLineWidth(1);
        //    if(isFit) bkgFit_1->Draw("same");

        // ++++ legend
        pLegCategory->Draw("same");


        //    legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih]," Global-Global", " ");

        legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih]," |#eta^{#mu}| < 2.4, p_{T}^{#mu} > 10 GeV/c ", "");
        legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih]," Unlike Sign ", "LP");
        legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPtS[ih]," Like Sign ", "LP");
        legend_1[ih]->AddEntry(Zmumu," pp Data ", "L");




        //    legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], text, "");


        sprintf(szBuf, "N=%1.0f #pm %1.1f ", yld_cat_1[ih], sqrt(yld_cat_1[ih]) );

        legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], szBuf, "");

        //    sprintf(label_1, "N_{Z^{0}} = 27");

        sprintf(szBuf, "mass = %1.2f #pm %1.2f GeV/c^{2}", RBWPOL->GetParameter(1), RBWPOL->GetParError(1));
        //    if(isFit) legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih],szBuf, "");

        sprintf(szBuf, "#sigma_{Gauss} = %1.2f #pm %1.2f GeV/c^{2}", RBWPOL->GetParameter(2), RBWPOL->GetParError(2));

        if(nFitFunction ==3 || nFitFunction  == 4)
            sprintf(szBuf, "#sigma_{Gauss} = %1.2f #pm %1.2f GeV/c^{2}", RBWPOL->GetParameter(3), RBWPOL->GetParError(3));

        //    if(isFit) legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], szBuf, "");

        sprintf(szBuf, "#chi^{2}/ndf = %1.2f / %d", chisq, ndf);

        //    if(isFit) legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], label_4, "");

        legend_1[ih]->Draw("same");

        pcPt_1->Update();
    }

    cout << endl << endl;


    TGraphErrors *Z0pt_cat_1 = new TGraphErrors(nBins, PT, yld_cat_1, mom_err, eyld_cat_1);
    Z0pt_cat_1->SetMarkerStyle(20);
    Z0pt_cat_1->SetMarkerColor(2);
    Z0pt_cat_1->GetXaxis()->SetTitle(label);
    Z0pt_cat_1->GetYaxis()->SetTitle("counts");

    TCanvas *pc2 = new TCanvas("pc2","pc2");
    Z0pt_cat_1->SetMinimum(0.0);
    Z0pt_cat_1->SetName("Z0pt_cat_1");
    Z0pt_cat_1->Draw("AP");


    TGraphErrors *Z0ptC_cat_1_gen = new TGraphErrors(nBins, PT, gen_pt, mom_err, egen_pt);
    //  Z0ptC_cat_1_gen->SetMarkerStyle(23);
    //Z0ptC_cat_1_gen->SetMarkerColor(3);
    //Z0ptC_cat_1_gen->Draw("AP");


    pLegCategory->Draw("same");

    Z0pt_cat_1->Write();
    pLegCategory->Write();


    //    gPad->Print("Pt_Z0YieldCat_1.png");
    pcPt_1->Print("Pt_Z0YieldCat_1.png");


    cout << endl << endl;




    //////////////////////////////////////////////////////////////////////////////

    // Efficiency correction
    if(doMc)  {
        ofstream fileout("correction.txt");
        cout << label << "   Eff_cat_1  " << endl;

        for (Int_t ih = 0; ih < nBins; ih++)  {
            Eff_cat_1[ih] = yld_cat_1[ih]/gen_pt[ih];

            errEff_cat_1[ih] = sqrt( (pow(Eff_cat_1[ih]/yld_cat_1[ih],2))*eyld_cat_1[ih]
                                     +(pow((1-Eff_cat_1[ih]/yld_cat_1[ih]),2))*( yld_cat_1[ih]-gen_pt[ih]/ yld_cat_1[ih]));
            //	  errEff_cat_1[ih] = sqrt( (pow(Eff_cat_1[ih]/yld_cat_1[ih],2))*eyld_cat_1[ih]
            //			   +(pow((1-Eff_cat_1[ih]/yld_cat_1[ih]),2))*event failing);


            //	fileout << PT[ih] <<"   "<< Eff_cat_1[ih] << "   " << Eff_cat_2[ih] <<"    " << Eff_cat_3[ih] << endl;
            //	cout <<"    " << PT[ih] <<"      "<< Eff_cat_1[ih] << "      " << Eff_cat_2[ih] << "      " << Eff_cat_3[ih] << endl;

            fileout << PT[ih] <<"   "<< Eff_cat_1[ih] << "   " << errEff_cat_1[ih] << endl;
            cout <<"    " << PT[ih] <<"    "<< Eff_cat_1[ih] << " +- " << errEff_cat_1[ih] << endl;
            cyld_cat_1[ih] = Eff_cat_1[ih];
            ceyld_cat_1[ih] = errEff_cat_1[ih];

        }
    }
    else {
        ifstream filein("correction.txt");
        cout <<  label << " yld_cat_1 "  << "  efficiency " <<  " corr. yld_cat_1  " << endl;
        for (Int_t ih = 0; ih < nBins; ih++)  {

            //      filein >> PT[ih] >>  Eff_cat_1[ih] >>  Eff_cat_2[ih]  >>  Eff_cat_3[ih] ;
            //      cout << "       " << PT[ih] << "      "<< yld_cat_1[ih] << "       " << yld_cat_2[ih] <<"      " <<  yld_cat_3[ih] << endl;

            filein >> PT[ih] >>  Eff_cat_1[ih]  >> errEff_cat_1[ih];
            cout << "    " << PT[ih] << "     " << yld_cat_1[ih] << "     " << Eff_cat_1[ih] << "     " << yld_cat_1[ih]/Eff_cat_1[ih] << endl;
            cyld_cat_1[ih] = yld_cat_1[ih]/Eff_cat_1[ih];
            ceyld_cat_1[ih] = eyld_cat_1[ih]/Eff_cat_1[ih];

        }
    }

    //  TF1 *EXPA = new TF1("EXPA", Exp, 0, 100, 2);

    TGraphErrors *Z0ptC_cat_1 = new TGraphErrors(nBins, PT, cyld_cat_1, mom_err, ceyld_cat_1);
    Z0ptC_cat_1->SetMarkerStyle(20);
    Z0ptC_cat_1->SetMarkerColor(2);
    Z0ptC_cat_1->GetXaxis()->SetTitle(label);
    Z0ptC_cat_1->GetYaxis()->SetTitle("Acc x Eff");
    //  if(part == 2) Z0ptC_cat_1->Fit("EXPA","LEQ", "", 7, 16);


    new TCanvas;
    Z0ptC_cat_1->SetMinimum(0.0);
    Z0ptC_cat_1->SetMaximum(0.8);
    Z0ptC_cat_1->SetName("Z0ptC_cat_1");
    Z0ptC_cat_1->Draw("AP");


    pLegCategory->Draw("same");

    cout << endl << endl;

    Z0ptC_cat_1->Write();

}
Example #24
0
CMasternodePaymentDB::ReadResult CMasternodePaymentDB::Read(CMasternodePayments& objToLoad, bool fDryRun)
{

    int64_t nStart = GetTimeMillis();
    // open input file, and associate with CAutoFile
    FILE *file = fopen(pathDB.string().c_str(), "rb");
    CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
    if (filein.IsNull())
    {
        error("%s : Failed to open file %s", __func__, pathDB.string());
        return FileError;
    }

    // use file size to size memory buffer
    int fileSize = boost::filesystem::file_size(pathDB);
    int dataSize = fileSize - sizeof(uint256);
    // Don't try to resize to a negative number if file is small
    if (dataSize < 0)
        dataSize = 0;
    vector<unsigned char> vchData;
    vchData.resize(dataSize);
    uint256 hashIn;

    // read data and checksum from file
    try {
        filein.read((char *)&vchData[0], dataSize);
        filein >> hashIn;
    }
    catch (std::exception &e) {
        error("%s : Deserialize or I/O error - %s", __func__, e.what());
        return HashReadError;
    }
    filein.fclose();

    CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION);

    // verify stored checksum matches input data
    uint256 hashTmp = Hash(ssObj.begin(), ssObj.end());
    if (hashIn != hashTmp)
    {
        error("%s : Checksum mismatch, data corrupted", __func__);
        return IncorrectHash;
    }


    unsigned char pchMsgTmp[4];
    std::string strMagicMessageTmp;
    try {
        // de-serialize file header (masternode cache file specific magic message) and ..
        ssObj >> strMagicMessageTmp;

        // ... verify the message matches predefined one
        if (strMagicMessage != strMagicMessageTmp)
        {
            error("%s : Invalid masternode payement cache magic message", __func__);
            return IncorrectMagicMessage;
        }


        // de-serialize file header (network specific magic number) and ..
        ssObj >> FLATDATA(pchMsgTmp);

        // ... verify the network matches ours
        if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
        {
            error("%s : Invalid network magic number", __func__);
            return IncorrectMagicNumber;
        }

        // de-serialize data into CMasternodePayments object
        ssObj >> objToLoad;
    }
    catch (std::exception &e) {
        objToLoad.Clear();
        error("%s : Deserialize or I/O error - %s", __func__, e.what());
        return IncorrectFormat;
    }

    LogPrintf("Loaded info from mnpayments.dat  %dms\n", GetTimeMillis() - nStart);
    LogPrintf("  %s\n", objToLoad.ToString());
    if(!fDryRun) {
        LogPrintf("Masternode payments manager - cleaning....\n");
        objToLoad.CleanPaymentList();
        LogPrintf("Masternode payments manager - result:\n");
        LogPrintf("  %s\n", objToLoad.ToString());
    }

    return Ok;
}
Example #25
0
bool MODEL::ReadFromFile(const std::string & filepath, std::ostream & error_output, bool generatelistid)
{
	const bool verbose = false;
	
	if (verbose) std::cout << filepath << ": starting mesh read" << std::endl;
	
	std::ifstream filein(filepath.c_str(), std::ios_base::binary);
	if (!filein)
	{
		error_output << "Can't find file: " << filepath << std::endl;
		return false;
	}
	//else std::cout << "File " << filepath << " exists!" << std::endl;
	
	const std::string magic = "OGLVARRAYV01";
	const int magicsize = 12;//magic.size();
	char fmagic[magicsize+1];
	filein.read(fmagic, magic.size());
	if (!filein)
	{
		error_output << "File magic read error: " << filepath << std::endl;
		return false;
	}
	
	fmagic[magic.size()] = '\0';
	std::string fmagicstr = fmagic;
	if (magic != fmagic)
	{
		error_output << "File magic is incorrect: \"" << magic << "\" != \"" << fmagic << "\" in " << filepath << std::endl;
		return false;
	}
	
	if (verbose) std::cout << filepath << ": serializing" << std::endl;
	
	/*// read the entire file into the memfile stream
	std::streampos start = filein.tellg();
	filein.seekg(0,std::ios::end);
	std::streampos length = filein.tellg() - start;
	filein.seekg(start);
	std::vector <char> buffer(length);
	filein.read(&buffer[0],length);
	std::stringstream memfile;
	memfile.rdbuf()->pubsetbuf(&buffer[0],length);*/
	
	joeserialize::BinaryInputSerializer s(filein);
	//joeserialize::BinaryInputSerializer s(memfile);
	if (!Serialize(s))
	{
		error_output << "Serialization error: " << filepath << std::endl;
		Clear();
		return false;
	}
	
	if (verbose) std::cout << filepath << ": generating metrics" << std::endl;
	
	ClearListID();
	ClearMetrics();
	GenerateMeshMetrics();
	if (verbose) std::cout << filepath << ": generating list id" << std::endl;
	//if (generatelistid)
		//GenerateListID(error_output);
	
	if (verbose) std::cout << filepath << ": done" << std::endl;
	
	return true;
}
Example #26
0
void createProbingPT(const char * phrasetable_path, const char * target_path){
    //Get basepath and create directory if missing
    std::string basepath(target_path);
    mkdir(basepath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

    //Set up huffman and serialize decoder maps.
    Huffman huffmanEncoder(phrasetable_path); //initialize
    huffmanEncoder.assign_values();
    huffmanEncoder.produce_lookups();
    huffmanEncoder.serialize_maps(target_path);

    //Get uniq lines:
    unsigned long uniq_entries = huffmanEncoder.getUniqLines();

    //Source phrase vocabids
    std::map<uint64_t, std::string> source_vocabids;

    //Read the file
    util::FilePiece filein(phrasetable_path);

    //Init the probing hash table
    size_t size = Table::Size(uniq_entries, 1.2);
    char * mem = new char[size];
    memset(mem, 0, size);
    Table table(mem, size);

    BinaryFileWriter binfile(basepath); //Init the binary file writer.

    line_text prev_line; //Check if the source phrase of the previous line is the same

    //Keep track of the size of each group of target phrases
    uint64_t entrystartidx = 0;
    //uint64_t line_num = 0;


    //Read everything and processs
    while(true){
        try {
            //Process line read
            line_text line;
            line = splitLine(filein.ReadLine());
            //Add source phrases to vocabularyIDs
            add_to_map(&source_vocabids, line.source_phrase);

            if ((binfile.dist_from_start + binfile.extra_counter) == 0) {
                prev_line = line; //For the first iteration assume the previous line is
            } //The same as this one.

            if (line.source_phrase != prev_line.source_phrase){

                //Create a new entry even

                //Create an entry for the previous source phrase:
                Entry pesho;
                pesho.value = entrystartidx;
                //The key is the sum of hashes of individual words. Probably not entirerly correct, but fast
                pesho.key = 0;
                std::vector<uint64_t> vocabid_source = getVocabIDs(prev_line.source_phrase);
                for (int i = 0; i < vocabid_source.size(); i++){
                    pesho.key += vocabid_source[i];
                }
                pesho.bytes_toread = binfile.dist_from_start + binfile.extra_counter - entrystartidx;

                //Put into table
                table.Insert(pesho);

                entrystartidx = binfile.dist_from_start + binfile.extra_counter; //Designate start idx for new entry

                //Encode a line and write it to disk.
                std::vector<unsigned char> encoded_line = huffmanEncoder.full_encode_line(line);
                binfile.write(&encoded_line);

                //Set prevLine
                prev_line = line;

            } else{
                //If we still have the same line, just append to it:
                std::vector<unsigned char> encoded_line = huffmanEncoder.full_encode_line(line);
                binfile.write(&encoded_line);
            }

        } catch (util::EndOfFileException e){
            std::cerr << "Reading phrase table finished, writing remaining files to disk." << std::endl;
            binfile.flush();

            //After the final entry is constructed we need to add it to the phrase_table
            //Create an entry for the previous source phrase:
            Entry pesho;
            pesho.value = entrystartidx;
            //The key is the sum of hashes of individual words. Probably not entirerly correct, but fast
            pesho.key = 0;
            std::vector<uint64_t> vocabid_source = getVocabIDs(prev_line.source_phrase);
            for (int i = 0; i < vocabid_source.size(); i++){
                pesho.key += vocabid_source[i];
            }
            pesho.bytes_toread = binfile.dist_from_start + binfile.extra_counter - entrystartidx;
            //Put into table
            table.Insert(pesho);

            break;
        }
    }

    serialize_table(mem, size, (basepath + "/probing_hash.dat").c_str());

    serialize_map(&source_vocabids, (basepath + "/source_vocabids").c_str());
    
    delete[] mem;

    //Write configfile
    std::ofstream configfile;
    configfile.open((basepath + "/config").c_str());
    configfile << uniq_entries << '\n';
    configfile.close();
}
Example #27
0
int main(int argc, char **argv) {
  printf("ERKALE - Basis set tools from Hel.\n");
  print_copyright();
  print_license();
#ifdef SVNRELEASE
  printf("At svn revision %s.\n\n",SVNREVISION);
#endif
  print_hostname();

  if(argc<3) {
    printf("Usage: %s input.gbs command\n\n",argv[0]);
    help();
    return 0;
  }

  // Get filename
  std::string filein(argv[1]);
  // Load input
  BasisSetLibrary bas;
  bas.load_gaussian94(filein);

  // Get command
  std::string cmd(argv[2]);
  // and determine what to do.
  if(stricmp(cmd,"cholesky")==0) {
    // Print completeness profile.

    if(argc!=7) {
      printf("\nUsage: %s input.gbs cholesky thr maxam ovlthr output.gbs\n",argv[0]);
      return 1;
    }

    double thr(atof(argv[3]));
    int maxam(atoi(argv[4]));
    double ovlthr(atof(argv[5]));
    std::string outfile(argv[6]);

    if(maxam>=LIBINT_MAX_AM) {
      printf("Setting maxam = %i because limitations in used version of LIBINT.\n",LIBINT_MAX_AM-1);
      maxam=LIBINT_MAX_AM-1;
    }
			       
    init_libint_base();
    BasisSetLibrary ret=bas.cholesky_set(thr,maxam,ovlthr);
    ret.save_gaussian94(outfile);
    
  } else if(stricmp(cmd,"completeness")==0) {
    // Print completeness profile.

    if(argc!=5 && argc!=6) {
      printf("\nUsage: %s input.gbs completeness element output.dat (coulomb)\n",argv[0]);
      return 1;
    }

    std::string el(argv[3]);
    std::string fileout(argv[4]);
    bool coulomb=false;
    if(argc==6)
      coulomb=atoi(argv[5]);

    // Get wanted element from basis
    ElementBasisSet elbas=bas.get_element(el);

    // Compute completeness profile
    compprof_t prof=compute_completeness(elbas,-10.0,10.0,2001,coulomb);

    // Print profile in output file
    FILE *out=fopen(fileout.c_str(),"w");
    for(size_t i=0;i<prof.lga.size();i++) {
      // Value of scanning exponent
      fprintf(out,"%13e",prof.lga[i]);
      // Print completeness of shells
      for(size_t j=0;j<prof.shells.size();j++)
	fprintf(out,"\t%13e",prof.shells[j].Y[i]);
      fprintf(out,"\n");
    }
    fclose(out);

  } else if(stricmp(cmd,"composition")==0) {
    // Determine composition of basis set.

    if(argc!=3 && argc!=4) {
      printf("\nUsage: %s input.gbs composition (El)\n",argv[0]);
      return 1;
    }

    // Elemental basis sets
    std::vector<ElementBasisSet> elbases;

    if(argc==4)
      elbases.push_back(bas.get_element(argv[3]));
    else
      elbases=bas.get_elements();

    printf("\n");
    printf("el at#  [npr|nbf] [primitive|contracted(?)]\n");
    printf("-------------------------------------------\n");

    // Loop over elements
    for(size_t iel=0;iel<elbases.size();iel++) {
      // Get the basis set
      ElementBasisSet elbas=elbases[iel];

      // Decontracted basis
      ElementBasisSet eldec(elbas);
      eldec.decontract();

      // Get the shells
      std::vector<FunctionShell> sh=elbas.get_shells();
      std::vector<FunctionShell> decsh=eldec.get_shells();

      // Count the shells
      arma::imat Nsh(max_am,2);
      Nsh.zeros();
      for(size_t ish=0;ish<decsh.size();ish++)
	Nsh(decsh[ish].get_am(),0)++;
      for(size_t ish=0;ish<sh.size();ish++)
	Nsh(sh[ish].get_am(),1)++;

      // Determine if basis set is contracted and the amount of
      // functions
      bool contr=false;
      size_t nbf=0;
      size_t nprim=0;
      for(int am=0;am<max_am;am++) {
	// Number of primitives
	nprim+=Nsh(am,0)*(2*am+1);
	// Number of contracted functions
	nbf+=Nsh(am,1)*(2*am+1);
      }
      if(nbf!=nprim)
	contr=true;

      // Print composition
      printf("%-2s %3i ",elbas.get_symbol().c_str(),(int) elbas.get_number());
      if(contr) {
	// Print amount of functions
	char cmp[20];
	sprintf(cmp,"[%i|%i]",(int) nprim,(int) nbf);
	printf("%10s [",cmp);

	// Print primitives
	for(int am=0;am<max_am;am++)
	  if(Nsh(am,0)>0)
	    printf("%i%c",Nsh(am,0),tolower(shell_types[am]));
	// Print contractions
	printf("|");
	for(int am=0;am<max_am;am++)
	  if(Nsh(am,0)!=Nsh(am,1))
	    printf("%i%c",Nsh(am,1),tolower(shell_types[am]));
	printf("]\n");
      } else {
	printf("%10i  ",(int) nbf);
	for(int am=0;am<max_am;am++)
	  if(Nsh(am,0)>0)
	    printf("%i%c",Nsh(am,0),tolower(shell_types[am]));
	printf("\n");
      }
    }
  } else if(stricmp(cmd,"daug")==0 || stricmp(cmd,"taug")==0) {
    // Augment basis set

    if(argc!=4) {
      printf("\nUsage: %s input.gbs %s output.gbs\n",argv[0],tolower(cmd).c_str());
      return 1;
    }

    int naug;
    if(stricmp(cmd,"daug")==0)
      naug=1;
    else
      naug=2;

    std::string fileout(argv[3]);
    bas.augment(naug);
    bas.save_gaussian94(fileout);
  } else if(stricmp(cmd,"decontract")==0) {
  // Decontract basis set.

    if(argc!=4) {
      printf("\nUsage: %s input.gbs decontract output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout(argv[3]);
    bas.decontract();
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"densityfit")==0) {
  // Generate density fitted set

    if(argc!=6) {
      printf("\nUsage: %s input.gbs densityfit lval fsam output.gbs\n",argv[0]);
      return 1;
    }

    int lval(atoi(argv[3]));
    double fsam(atof(argv[4]));
    std::string fileout(argv[5]);
    BasisSetLibrary dfit(bas.density_fitting(lval,fsam));
    dfit.save_gaussian94(fileout);

  } else if(stricmp(cmd,"dump")==0) {
    // Dump wanted element.

    if(argc!=5 && argc!=6) {
      printf("\nUsage: %s input.gbs dump element output.gbs (number)\n",argv[0]);
      return 1;
    }

    std::string el(argv[3]);
    std::string fileout(argv[4]);

    int no=0;
    if(argc==6)
      no=atoi(argv[5]);

    // Save output
    BasisSetLibrary elbas;
    elbas.add_element(bas.get_element(el,no));
    elbas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"dumpdec")==0) {
    // Dump wanted element in decontracted form.

    if(argc!=5 && argc!=6) {
      printf("\nUsage: %s input.gbs dumpdec element output.gbs (number)\n",argv[0]);
      return 1;
    }

    std::string el(argv[3]);
    std::string fileout(argv[4]);

    int no=0;
    if(argc==6)
      no=atoi(argv[5]);

    // Save output
    BasisSetLibrary elbas;
    bas.decontract();
    elbas.add_element(bas.get_element(el,no));
    elbas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"genbas")==0) {
    // Generate basis set for xyz file

    if(argc!=5) {
      printf("\nUsage: %s input.gbs genbas system.xyz output.gbs\n",argv[0]);
      return 1;
    }

    // Load atoms from xyz file
    std::vector<atom_t> atoms=load_xyz(argv[3]);
    // Output file
    std::string fileout(argv[4]);
    // Save output
    BasisSetLibrary elbas;

    // Collect elements
    std::vector<ElementBasisSet> els=bas.get_elements();
    // Loop over atoms in system
    for(size_t iat=0;iat<atoms.size();iat++) {
      bool found=false;

      // First, check if there is a special basis for the atom.
      for(size_t iel=0;iel<els.size();iel++)
	if(stricmp(atoms[iat].el,els[iel].get_symbol())==0 && atoms[iat].num == els[iel].get_number()) {
	  // Yes, add it.
	  elbas.add_element(els[iel]);
	  found=true;
	  break;
	}

      // Otherwise, check if a general basis is already in the basis
      if(!found) {
	std::vector<ElementBasisSet> added=elbas.get_elements();
	for(size_t j=0;j<added.size();j++)
	  if(added[j].get_number()==0 && stricmp(atoms[iat].el,added[j].get_symbol())==0)
	    found=true;
      }

      // If general basis not found, add it.
      if(!found) {
	for(size_t iel=0;iel<els.size();iel++)
	  if(stricmp(atoms[iat].el,els[iel].get_symbol())==0 && els[iel].get_number()==0) {
	    // Yes, add it.
	    elbas.add_element(els[iel]);
	    found=true;
	    break;
	  }
      }

      if(!found) {
	std::ostringstream oss;
	oss << "Basis set for element " << atoms[iat].el << " does not exist in " << filein << "!\n";
	throw std::runtime_error(oss.str());
      }
    }
    elbas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"merge")==0) {
    // Merge functions with too big overlap

    if(argc!=5) {
      printf("\nUsage: %s input.gbs merge cutoff output.gbs\n",argv[0]);
      return 1;
    }

    // Cutoff value
    double cutoff=atof(argv[3]);
    bas.merge(cutoff);
    bas.save_gaussian94(argv[4]);

  } else if(stricmp(cmd,"norm")==0) {
    // Normalize basis

    if(argc!=4) {
      printf("\nUsage: %s input.gbs norm output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.normalize();
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"orth")==0) {
    // Orthogonalize basis

    if(argc!=4) {
      printf("\nUsage: %s input.gbs orth output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.orthonormalize();
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"overlap")==0) {
    // Primitive overlap

    if(argc!=4) {
      printf("\nUsage: %s input.gbs overlap element\n",argv[0]);
      return 1;
    }

    // Get element basis set
    ElementBasisSet elbas=bas.get_element(argv[3]);
    elbas.decontract();

    // Loop over angular momentum
    for(int am=0;am<=elbas.get_max_am();am++) {
      // Get primitives
      arma::vec exps;
      arma::mat contr;
      elbas.get_primitives(exps,contr,am);

      // Compute overlap matrix
      arma::mat S=overlap(exps,exps,am);

      // Print out overlap
      printf("*** %c shell ***\n",shell_types[am]);
      exps.t().print("Exponents");
      printf("\n");

      S.print("Overlap");
      printf("\n");
    }

  } else if(stricmp(cmd,"Porth")==0) {
    // P-orthogonalize basis

    if(argc!=6) {
      printf("\nUsage: %s input.gbs Porth cutoff Cortho output.gbs\n",argv[0]);
      return 1;
    }

    double cutoff=atof(argv[3]);
    double Cortho=atof(argv[4]);
    std::string fileout=argv[5];
    bas.P_orthogonalize(cutoff,Cortho);
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"prodset")==0) {
    // Generate product set
    
    if(argc!=6) {
      printf("\nUsage: %s input.gbs prodset lval fsam output.gbs\n",argv[0]);
      return 1;
    }

    int lval(atoi(argv[3]));
    double fsam(atof(argv[4]));
    std::string fileout(argv[5]);
    BasisSetLibrary dfit(bas.product_set(lval,fsam));
    dfit.save_gaussian94(fileout);
    
  } else if(stricmp(cmd,"save")==0) {
    // Save basis

    if(argc!=4) {
      printf("\nUsage: %s input.gbs save output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.save_gaussian94(fileout);

  } else if(stricmp(cmd,"savecfour")==0) {
    // Save basis in CFOUR format

    if(argc!=5) {
      printf("\nUsage: %s input.gbs savecfour name basis.cfour\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    std::string name=argv[4];
    bas.save_cfour(name,fileout);

  } else if(stricmp(cmd,"savedalton")==0) {
    // Save basis in Dalton format

    if(argc!=4) {
      printf("\nUsage: %s input.gbs savedalton output.dal\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.save_dalton(fileout);

  } else if(stricmp(cmd,"savemolpro")==0) {
    // Save basis in Molpro format

    if(argc!=4) {
      printf("\nUsage: %s input.gbs savemolpro output.mol\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.save_molpro(fileout);

  } else if(stricmp(cmd,"sort")==0) {
    // Sort basis set

    if(argc!=4) {
      printf("\nUsage: %s input.gbs sort output.gbs\n",argv[0]);
      return 1;
    }

    std::string fileout=argv[3];
    bas.sort();
    bas.save_gaussian94(fileout);
  } else {
    printf("\nInvalid command.\n");

    help();
  }

  return 0;
}
Example #28
0
//bool MainWindow::CopyRaw(QByteArray src,QByteArray dst,int blockstart,int blockend)
bool MainWindow::CopyRaw(QByteArray src,QByteArray dst,int entry)
{
    int copyunitblock = 128;
    int size;
    unsigned char buffer[copyunitblock*512];
    unsigned blockstart = filesystem.logentry[entry].blockstart;
    unsigned blockend = filesystem.logentry[entry].blockend;
    int nblockstocopy = blockend-blockstart+1;      // Number of blocks to copy
    int nblockscopied = 0;                          // Blocks copied so far
    bool ok;
    int len;
    qint64 len64;
    QString title = QString("Exporting log on %1[%2-%3] to %4").arg(QString(src)).arg(blockstart).arg(blockend).arg(QString(dst));


    // Input / output files
    LowLevelFile filein(src);
    filein.open();
    QFile fileout(dst);
    fileout.open(QIODevice::WriteOnly|QIODevice::Truncate);

    // Progress dialog
    QProgressDialog pd(title,"Abort export", 0, nblockstocopy, this,Qt::Tool);
    pd.setWindowModality(Qt::WindowModal);
    pd.setAutoReset(false);

    // First copy the ROOT
    strcpy((char*)buffer,"LOG");
    fileout.write((char*)buffer,4);
    memset(buffer,0,10);
    fileout.write((char*)buffer,10);
    // Copy the log entry
    printf("Writing logentry. Sizeof: %d\n",sizeof(fs_logentry));
    printf("sizeof logentry: %d\n",sizeof(fs_logentry));
    fileout.write((char*)&filesystem.logentry[entry],sizeof(fs_logentry));


    unsigned long long o,no;
    o = blockstart;
    o<<=9;
    ok = filein.seek(o,no);
    if(!ok)
    {
        QMessageBox::critical(this,title,"Error seeking card");
        return false;
    }

    printf("Copying %d blocks\n",nblockstocopy);
    while(nblockscopied < nblockstocopy)
    {
        if (pd.wasCanceled())
            break;
        pd.setValue(nblockscopied);

        // See how many blocks we can copy
        //printf("unit: %d. nblockscopied: %d. nblockstocopy: %d\n",copyunitblock,nblockscopied,nblockstocopy);
        while( nblockscopied+copyunitblock > nblockstocopy)
        {
            copyunitblock>>=1;
            //printf("Resize unit. unit: %d. nblockscopied: %d. nblockstocopy: %d\n",copyunitblock,nblockscopied,nblockstocopy);
        }
        //printf("copyunitblock is now: %d\n",copyunitblock);

        size = copyunitblock*512;
        ok = filein.read(size,buffer,len);
        if(!ok || len!=size)
        {
            QMessageBox::critical(this,title,"Error reading card");
            return false;
        }
        len64 = fileout.write((char*)buffer,size);
        if(len64!=size)
        {
            QMessageBox::critical(this,title,"Error writing log");
            return false;
        }
        nblockscopied += copyunitblock;
    }
    bool cancelled = pd.wasCanceled();
    printf("Copy done. cancelled: %d\n",cancelled);
    filein.close();
    fileout.close();
    pd.close();
    if(cancelled)
        return false;
    return true;
}
Example #29
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;

}