diff --git a/Utils/EQM/MLP_Kinf/Generate_MLP_Kinf.cxx b/Utils/EQM/MLP_Kinf/Generate_MLP_Kinf.cxx new file mode 100644 index 0000000000000000000000000000000000000000..cac3ae35024e0bbb037e7a0e05833b1d48efbf1a --- /dev/null +++ b/Utils/EQM/MLP_Kinf/Generate_MLP_Kinf.cxx @@ -0,0 +1,835 @@ +/**********************************************************/ +// Make the input file for the MLPs training +// +// This programs reads a set of .dat files which are the +// results of a depletion calculation (see manual and +// looks for XS_CLOSEST). From the reading it fills a +// TTree (Data) and write it in a file named +// TrainingInput.root . +// OUTPUTS : +// 1- File TrainingInput.cxx is the list of MLP outputs +// (cross sections) +// 2- File TrainingInput.root input datas (as a Root TTREE) for MLP training +// 3- File Data_Base_Info.nfo Information file to be red by XSM_MLP +// (to be place in the weight folder which is build by MLP training) +// +//@author BaM, BaL +/**********************************************************/ +#include "include/Generate_MLP_Kinf.hxx" +#include <TH1F.h> +#include <TH2D.h> +#include <TFile.h> +#include <TTree.h> +#include "../../../source/external/StringLine.hxx" +#include <TString.h> +#include <string> +#include <cmath> +#include <math.h> +#include <iostream> +#include <fstream> +#include <algorithm> +#include <map> +#include <sstream> +#include <numeric> +#include <functional> +#include <algorithm> +#include <ctime> + +using namespace std; + +ZAIMass cZAIMass; //atomic masses + +string ElNames[110]={" ","H","He","Li","Be", + "B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar", + "K","Ca","Sc","Ti","V ","Cr","Mn","Fe","Co","Ni","Cu","Zn","Ga","Ge", + "As","Se","Br","Kr","Rb","Sr","Y","Zr","Nb","Mo","Tc","Ru","Rh","Pd", + "Ag","Cd","In","Sn","Sb","Te","I","Xe","Cs","Ba","La","Ce","Pr","Nd", + "Pm","Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb","Lu","Hf","Ta","W", + "Re","Os","Ir","Pt","Au","Hg","Tl","Pb","Bi","Po","At","Rn","Fr","Ra", + "Ac","Th","Pa","U","Np","Pu","Am","Cm","Bk","Cf","Es","Fm","Md","No", + "Lr","Rf","Db","Sg","Bh","Hs","Mt"}; + +//-------------------------------------------------------------------------------------------------- +/************************* + MAIN +*************************/ +int main(int argc, char ** argv) +{ + + if(argc!=2) + { + cout << "Usage : Generate_MLP_Kinf Path" << endl; + cout << " Where Path is the path to the folder containing Evolution Datas" << endl; + cout << " i.e the (.dat) files" << endl; + exit(0); + } + + /*****************Preparation of working folders*************************/ + if(is_file_exist("Training_output_0.root" )) + { + cout<< "Trainining_output* detected. Delete these files and weights folder ? [y/n]"<<endl; + if(UserSayYes()) + system( "rm -rf Training_output* weights" ); + else + { cout << "Move this files elsewhere and run this program again"<<endl; + exit(0); + } + } + + if(is_file_exist("_tmp/include_Train/TrainingInput.cxx" )) + system( "rm -rf _tmp" ); + + system("mkdir -p _tmp/include_Train"); + /**********************************************************************/ + + fEvolutionDataFolder = argv[1]; + CheckJob(); // looks fot the .dat files in the fEvolutionDataFolder + + cout << endl; + cout << "â•â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â•®" << endl; + cout << "│ Load your EvolutionDatas to R.A.M │" << endl; + cout << "╰───────────────────────────────────────────────╯" << endl; + cout<<endl; + for(int i = 0; i < (int)JobName.size(); i++) + { + ReadAndFill(JobName[i]); + ProgressBar(i,JobName.size()); + } + ProgressBar(1,1); + + FillMapName(); + + cout << "Proportion of data to be used for training ? ]0-100[" <<endl; + double ProportionOfTraining = 0 ; + cin >> ProportionOfTraining ; + DumpInputNeuron("_tmp/include_Train/TrainingInput.root"); + Generate_tmva_factory_input(ProportionOfTraining); + + string ModelName = CreateInfoFile(); + + cout << "â•â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â•®" << endl; + cout << "│ GENERATED FILES: │" << endl; + cout << "├─────────────────────────────────────────────────────────────────────┤" << endl; + cout << "│#1 Input for TMVA training: \033[36m_tmp/include_Train/TrainingInput.root\033[0m │" << endl; + cout << "│#3 Model Information for CLASS: \033[36m"+ ModelName +".nfo\033[0m │" << endl; + cout << "╰─────────────────────────────────────────────────────────────────────╯" << endl; + cout << endl; + cout << "â•â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â•®" << endl; + cout << "│ NEXT STEPS: │" << endl; + cout << "├────────────────────────────────────────────────┤" << endl; + cout << "│1. Train your MLPs with \033[36mTrain.cxx\033[0m │" << endl; + cout << "│2. Test MLPs performances using informations in:│" << endl; + cout << "│ \033[36mUtils/XSM/MLP/Test/EvaluateTrainingCommands.dat\033[0m│" << endl; + cout << "│3. Put the file #3 in \033[36mweights\033[0m folder then │" << endl; + cout << "│ move this folder to $CLASS_PATH/DATA_BASES"<<fReactorType<<"/"<<fFuelType << "/EQModel/ChooseAName │" << endl; + cout << "╰────────────────────────────────────────────────╯" << endl; + cout << endl; + cout << "=> Doing the first step for you. Do you want to train the MLP on your local machine ? [y/n]" << endl; + + if(UserSayYes()) + { + CompileTraining(); + cout << "Let's train locally ? [y/n]" <<endl; + if(UserSayYes()) + system("./train"); + else + { + cout << "You can run it latter with ./Train" <<endl; + exit(0); + } + } + + + + +} +//-------------------------------------------------------------------------------------------------- +bool is_file_exist(const char *fileName) +{ + std::ifstream infile(fileName); + return infile.good(); +} +//-------------------------------------------------------------------------------------------------- +void CompileTraining() +{ + cout << "â•â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â•®" << endl; + cout << "│ COMPLILING TMVA TRAINING PROGRAM │" << endl; + cout << "╰────────────────────────────────────────────────╯" << endl; + if(is_file_exist("Train_XS")) + system("rm Train_XS "); + + string CMD = "g++ -o Train `root-config --cflags` Train.cxx `root-config --glibs` -lTMVA"; + cout << CMD <<endl; + system(CMD.c_str()); + + if(!is_file_exist("Train_XS")) + { + cout <<"\033[31m COMPILATION FAILED !!! May be not the good compilator name nor the good path of file to compile ? \033[0m " << endl; + exit(1); + } + else + cout <<"\t \033[32m Done \033[0m " << endl; + + +} + +//-------------------------------------------------------------------------------------------------- +//Convert int to string +string itoa(int num) +{ + ostringstream os(ostringstream::out); + os << num; + return os.str(); +} +//-------------------------------------------------------------------------------------------------- +//Give a name to a cross section +//!!!!!!!!!!!!!!!!!!!!!!!!!!// +// YOU MUST KEEP THE FORMAT : +// XS_Z_A_I_fis (fission cross section) +// XS_Z_A_I_cap (n,gamma cross section) +// XS_Z_A_I_n2n (n,2n cross section) +//!!!!!!!!!!!!!!!!!!!!!!!!!!// +string NameXS(ZAI act,string xs) +{ + stringstream Name; + Name<<"XS_"<<act.Z<<"_"<<act.A<<"_"<<act.I<<"_"<<xs; + + return Name.str(); +} + +//-------------------------------------------------------------------------------------------------- +void FillMapName() +{ + cout<<endl; + cout<< "â•â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â•®"<<endl; + cout<< "│ SET UP MLPs INPUT │"<<endl; + cout<< "│default : composition @ t=0 + Irradiation time │"<<endl; + cout<< "╰───────────────────────────────────────────────╯"<<endl; + cout<<endl; + + vector<ZAI> ZAI_T0 = fActinideCompoInit[0].GetNonZeroZAIList(); + + for(int zai = 0 ; zai < ZAI_T0.size() ; zai++ ) + { stringstream ssname; + int Z = ZAI_T0[zai].Z; + int A = ZAI_T0[zai].A; + int I = ZAI_T0[zai].I; + string sI=""; + if(I == 1) + sI = "m"; + else if(I == 2) + sI = "2m"; + else if(I == 3) + sI = "3m"; + + ssname<<A<<ElNames[Z]<<sI; + if(zai == 0) + cout<< "Add this nuclei with this name [y/n] ? (if you don't know type yes to all) "<<endl; + else + cout<< "Add [y/n] ? "<<endl; + + cout<< "[Z\tA\tI\tName]"<<endl; + cout<<"\033[36m"<<Z<<"\t"<<A<<"\t"<<I<<"\t"<<ssname.str()<<"\033[0m"<<endl; + + if (UserSayYes()) + { + fMapName.insert(pair<ZAI,string> ( ZAI(Z,A,I) , ssname.str()) ); + cout << "Is this nuclei is considered to be a part of a fissile element ? [y/n]" <<endl; + + if (UserSayYes()) + fStreamList.push_back( ZAIStreamList(Z,A,I,"Fissile",1) ); + else + { + cout<<"So it is considered as fertile\n What is the default proportion of this nucleus in the fertile vector ? [0-1] " <<endl; double Default_Proportion = 0; + cin >> Default_Proportion; + fStreamList.push_back( ZAIStreamList(Z,A,I,"Fertile",Default_Proportion) ); + } + cout<<endl; + } + } + + bool UserWantToAdd = true; + while(UserWantToAdd) + { + cout<< "Do you want to add additional nuclei [y/n] ? (if you don't know type no) "<<endl; + if(UserSayYes()) + { + int Z = 0; + int A = 0; + int I = 0; + string Name; + cout << " Z -> "; cin >> Z ; cout <<" A -> "; cin >> A ; cout <<" I -> "; cin >> I ;cout <<" Name -> "; cin >> Name; + fMapName.insert(pair<ZAI,string> ( ZAI(Z,A,I) ,Name) ); + } + + else + UserWantToAdd = false; + } + + +} +//-------------------------------------------------------------------------------------------------- +void Generate_tmva_factory_input(double ProportionOfTraining) +{ + + ofstream InputNetwork("_tmp/include_Train/InputVariables.cxx"); + for(map<ZAI,string>::iterator it = fMapName.begin() ; it != fMapName.end() ; it++ ) + InputNetwork <<"factory->AddVariable( \"" << it->second << "\" , \"" << it->second << "\", \"IsotopicFraction\", 'F' );"<<endl; + InputNetwork <<"factory->AddVariable( \"Time\" , \"Time\" , \"seconds\", 'F' );"<<endl<<endl; + + ProportionOfTraining /=100; + InputNetwork <<"double PropTraining = "<< ProportionOfTraining <<";"<< endl; + + InputNetwork.close(); +} + +//-------------------------------------------------------------------------------------------------- +bool UserSayYes() +{ + bool AnswerIsNotGiven = true; + bool isYES = false; + while(AnswerIsNotGiven) + { + string answer; + std::getline(std::cin, answer); + + + if(answer == "y" || answer == "yes" || answer == "Yes" || answer == "Y") + { + isYES = true; + AnswerIsNotGiven = false; + } + else if (answer == "n" || answer == "no" || answer == "No" || answer == "N") + { + isYES = false; + AnswerIsNotGiven = false; + } + + else{ + cout << "Yes OR No ? "<<endl; + } + } + return isYES; +} + +//-------------------------------------------------------------------------------------------------- +string CreateInfoFile() +{ + + /**************************************************/ + // GETTING USER INFO + /**************************************************/ + double sum = 0 ; + for (int i=0 ; i < fHMMass.size() ; i++) + sum+=fHMMass[i]; + + double MeanHMMass = sum / (double)fHMMass.size(); + string Author,Mail,XSBase,HLCut,EnergyDisc,FPYBase,SABase,Geom,AddInfo,DepCode ; + double Power = 0, FissileFirstGuess = 0; + + + int start=0; + string AnInfoFile = JobName[0]; + int pos=AnInfoFile.find(".dat",start); + AnInfoFile.replace(pos,4,".info"); + + ReadInfo(AnInfoFile,fReactorType,fFuelType,Power); + + cout<<endl; + cout<<endl; + cout<<"â•â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â•®"<<endl; + cout<<"│ XSM_MLP .NFO FILE GENERATOR │"<<endl; + cout<<"╰───────────────────────────────────────────────╯"<<endl; + cout<<" Answer following questions "<<endl; + cout<<"-> Author(s) name(s) : "<<endl; + std::getline(std::cin, Author); + cout<<endl; + + cout<<"-> email adress(es) : "<<endl; + std::getline(std::cin, Mail); + cout<<endl; + + cout<<"-> Depletion code used : "<<endl; + std::getline(std::cin, DepCode); + cout<<endl; + + cout<<"-> Cross section data base (e.g ENSDF7.1) : "<<endl; + std::getline(std::cin, XSBase); + cout<<endl; + + cout<<"-> Fission yield data base (e.g ENSDF7.1) : "<<endl; + std::getline(std::cin, FPYBase); + cout<<endl; + + cout<<"-> S(alpha,beta) data base (e.g ENSDF7.1) : "<<endl; + std::getline(std::cin, SABase); + cout<<endl; + + cout<<"-> Geometry simulated (e.g Cubic Assembly with mirror boundary) : "<<endl; + std::getline(std::cin, Geom); + cout<<endl; + + cout<<"-> Half life cut [s] (if any) : "<<endl; + std::getline(std::cin, HLCut); + cout<<endl; + + cout<<"-> Multi group treatment (yes/no if yes give the number of groups) : "<<endl; + std::getline(std::cin, EnergyDisc); + cout<<endl; + + cout<<"-> Additional informations : "<<endl; + std::getline(std::cin, AddInfo); + cout<<endl; + + + cout<<"-> Reactor type (e.g PWR, FBR,...) : "<<endl; + cout<<"Found in a .info file :"<<endl; + cout<<"\033[36m"<<fReactorType<<"\033[0m"<<endl; + cout<< "Is that corect ? [y/n] "<<endl; + if(!UserSayYes()) + { cout<<"\t So what it is ?"<<endl; + cin>> fReactorType; + } + cout<<endl; + + cout<<"-> Fuel type (e.g UOX, MOX,...) : "<<endl; + cout<<"Found in a .info file :"<<endl; + cout<<"\033[36m"<<fFuelType<<"\033[0m"<<endl; + cout<< "Is that corect ? [y/n] "<<endl; + if(!UserSayYes()) + { cout<<"\t So what it is ?"<<endl; + cin>> fFuelType; + } + cout<<endl; + + cout<<"-> Simulated heavy metal mass (tons) : "<<endl; + cout<< "\t According your evolution datas the AVERAGE heavy metal mass is : "<<endl; + cout<<"\033[36m"<<MeanHMMass<<"\033[0m"<<" tons"<<endl; + cout<< "Is that corect ? [y/n] "<<endl; + if(!UserSayYes()) + { cout<<"\t So what it is ?"<<endl; + cin>> MeanHMMass; + } + cout<<endl; + + cout<<"-> Simulated thermal power (W) : "<<endl; + cout<<"Found in a .info file :"<<endl; + cout<<"\033[36m"<<Power<<"\033[0m"<<endl; + cout<< "Is that corect ? [y/n] "<<endl; + if(!UserSayYes()) + { cout<<"\t So what it is ?"<<endl; + cin>> Power; + } + cout<<endl; + + cout<<"-> First guess of fissile content in fresh fuel (for algorithm initialization): ]0-1[ "<<endl; + cin>> FissileFirstGuess; + + cout<<endl; + + + /**************************************************/ + // BUILDING FILE + /**************************************************/ + stringstream ssModelName; + ssModelName << fReactorType << "_" << fFuelType << "_" << Power/(MeanHMMass*1e6) << "Wg"; + + + ofstream InfoFile( (ssModelName.str() + ".nfo").c_str()); + + InfoFile << "To be used with : EQM_PWR_MLP_Kinf.cxx " << endl; + InfoFile << "with constructor : EQM_PWR_MLP_Kinf(string TMVAWeightPath, int NumOfBatch, string InformationFile, double CriticalityThreshold)" << endl; + InfoFile <<"============================================" << endl; + InfoFile <<" Informations needed by EQM_MLP_Kinf model " <<endl; + InfoFile <<"============================================" << endl; + InfoFile << endl; + InfoFile << "Reactor Type :"<<endl; + InfoFile << "K_REACTOR "<< fReactorType <<endl; + InfoFile << endl; + InfoFile << "Fuel Type :"<<endl; + InfoFile << "K_FUEL "<< fFuelType <<endl; + InfoFile << endl; + InfoFile << "Specific Power (W/gHM) :"<<endl; + InfoFile << "K_SPECPOWER "<< Power/(MeanHMMass*1e6) <<endl; + InfoFile << endl; + + double IrrTimeMax = 0; + for(int i = 0 ; i < fTime.size() ; i++ ) + { + if (IrrTimeMax < fTime[i].back()) + IrrTimeMax = fTime[i].back(); + } + double Bu_Max = Power*1e-9 * (IrrTimeMax/3600./24.) / MeanHMMass; + InfoFile << "Maximal Burnup:"<<endl; + InfoFile << "K_MAXFISCONTENT "<< Bu_Max*1.2 <<endl; + InfoFile << endl; + + + InfoFile << "Z A I Name (input MLP) :"<<endl; + for(map<ZAI,string>::iterator it = fMapName.begin() ; it != fMapName.end() ; it++ ) + InfoFile <<"K_ZAINAME "<<it->first.Z <<" " <<it->first.A <<" " <<it->first.I<<" " << it->second <<endl ; + InfoFile <<endl; + + InfoFile << "Name of stream for fabrication (fissile or fertile):"<<endl; + InfoFile << "Z A I Default_Proportion" <<endl; + for( int l = 0 ; l < (int) fStreamList.size() ; l++ ) + InfoFile <<"K_LIST "<<fStreamList[l].fZAI.Z <<" " << fStreamList[l].fZAI.A <<" " <<fStreamList[l].fZAI.I<<" " << fStreamList[l].fListName <<" "<< fStreamList[l].fDefaultProportion<< endl ; + InfoFile <<endl; + + InfoFile << "Starting fissile content in fuel for equivalence model calculation :"<<endl; + InfoFile << "k_firstguesscontent Fissile " << FissileFirstGuess << endl; + InfoFile << "k_firstguesscontent Fertile " << 1 - FissileFirstGuess <<endl; + InfoFile << endl; + + InfoFile << "Fuel range (Z A I min max) :"<<endl; + for(map<ZAI,string>::iterator it = fMapName.begin() ; it != fMapName.end() ; it++ ) + { vector <double> AllCompoOfZAI = GetAllCompoOf(it->first); + vector <double>::iterator Min = std::min_element(AllCompoOfZAI.begin(),AllCompoOfZAI.end()); + vector <double>::iterator Max = std::max_element(AllCompoOfZAI.begin(),AllCompoOfZAI.end()); + InfoFile <<"K_ZAIL "<<it->first.Z <<" " <<it->first.A <<" " <<it->first.I<<" " << *Min << " " << *Max <<endl ; + } + InfoFile << endl; + InfoFile <<"============================================" << endl; + InfoFile <<" Data base generation informations " <<endl; + InfoFile <<"============================================" << endl; + InfoFile << endl; + time_t t = time(0); // get time now + struct tm * now = localtime( & t ); + InfoFile <<" Date: "<< now->tm_mday<< '/'<< (now->tm_mon + 1) << '/' <<(now->tm_year + 1900)<< endl; + InfoFile <<" Author(s): "<< Author <<endl; + InfoFile <<" Author(s) contact: "<< Mail <<endl; + InfoFile <<" Depletion code: "<< DepCode <<endl; + InfoFile <<" Simulated geometry: "<< Geom <<endl; + InfoFile <<" Nuclear data used in "<< DepCode <<endl; + InfoFile <<"\tCross section library: "<< XSBase <<endl; + InfoFile <<"\tFission yield library: "<< FPYBase <<endl; + InfoFile <<"\tS(alpha,beta) library: "<< SABase <<endl; + InfoFile <<" Half life cut [s] : "<< HLCut <<endl; + InfoFile <<" Multi-group treatment: "<< EnergyDisc <<endl; + InfoFile <<" Additional informations: "<< endl << AddInfo <<endl; + +return ssModelName.str(); + +} +//-------------------------------------------------------------------------------------------------- +vector<double> GetAllCompoOf(ZAI zai) +{ + vector<double> AllCompoOfZAI; + + for( int b = 0 ; b < fActinideCompoInit.size() ; b++ ) + AllCompoOfZAI.push_back(fActinideCompoInit[b].GetZAIIsotopicQuantity(zai)); + +return AllCompoOfZAI; +} +//-------------------------------------------------------------------------------------------------- +void ProgressBar(double loopindex, double totalindex) +{ + // Reset the line + //for(int i = 0; i < 22; i++) + // cout << " "; + cout << flush ; + + cout << "\033[42m"; + for(int i = 0; i < (int)(loopindex/totalindex*44.0); i++) + cout << " "; + cout<<" \033[41m"; + for(int i = 44; i >= (int)(loopindex/totalindex*44.0); i--) + cout << " "; + cout<<"\033[0m"; + cout << (int)(loopindex/totalindex*100) << "%\r"; + cout << flush; + //cout << endl; +} +//-------------------------------------------------------------------------------------------------- +void ReadInfo(string InfoDBFile,string &ReactorType,string &FuelType,double &Power) +{ + ifstream InfoDB(InfoDBFile.c_str()); // Open the File + if(!InfoDB) + { + cout << "\033[31m !!ERROR!! !!!EvolutionData!!! \n Can't open \"" << InfoDBFile << "\"\033[0m \n" << endl; + } + else + { + int start = 0; + string line; + getline(InfoDB, line); + string Next = StringLine::NextWord(line, start, ' '); + StringLine::ToLower(Next) ; + if ( Next == "reactor") + ReactorType = StringLine::NextWord(line, start, ' '); + + start = 0; + getline(InfoDB, line); + Next = StringLine::NextWord(line, start, ' '); + StringLine::ToLower(Next) ; + if ( Next == "fueltype") + FuelType = StringLine::NextWord(line, start, ' '); + + start = 0; + getline(InfoDB, line); + Next = StringLine::NextWord(line, start, ' '); + StringLine::ToLower(Next) ; + if ( Next == "cycletime") + double cycletime = atof(StringLine::NextWord(line, start, ' ').c_str()); + + getline(InfoDB, line); // Assembly HM Mass DONT TRUST THIS ONE CALCULATED WITH A instead of real atomic mass + + start = 0; + getline(InfoDB, line); + Next = StringLine::NextWord(line, start, ' '); + StringLine::ToLower(Next) ; + if ( Next == "constantpower") + Power = atof(StringLine::NextWord(line, start, ' ').c_str()); + InfoDB.close(); + } + +} + + +//-------------------------------------------------------------------------------------------------- +void DumpInputNeuron(string filename) +{ + TFile* fOutFile = new TFile(filename.c_str(),"RECREATE"); + TTree* fOutT = new TTree("Data", "Data"); + + +/**********************INITIALISATIONNN********************/ + + //////////////////////////////////////////////////////// + // INIT FRESH FUEL COMPOSITION and TIME + //////////////////////////////////////////////////////// + + double *FreshCompo = new double[fMapName.size()]; + + for(int i = 0 ; i < fMapName.size() ; i++ ) + FreshCompo[i] = 0; + + //////////////////////////////////////////////////////// + double Time = 0; + double k_inf = 0; + + +/**********************BRANCHING**************************************************/ +/**********************Fresh fuel**************************************************/ + + map<ZAI,string>::iterator it; + int index = 0; + for(it = fMapName.begin() ; it != fMapName.end() ; it++ ) + { string Name = it->second + "/D"; + fOutT->Branch( it->second.c_str() , &FreshCompo[index] , Name.c_str()); + index++; + } + + //////////////////////////////////////////////////////// + fOutT->Branch( "Time" ,&Time ,"Time/D" ); + fOutT->Branch( "k_inf" ,&k_inf ,"k_inf/D" ); + + +/**********************FILLING THE TTREE**************************************************/ + cout<<endl; + cout<<endl; + cout<<"â•â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â•®"<<endl; + cout<<"│ FILLING TTREE │"<<endl; + cout<<"│ (building TrainingInput.root) │"<<endl; + cout<<"╰───────────────────────────────────────────────╯"<<endl; + cout<<endl; + + int NumOfBase=fActinideCompoInit.size(); + for(int b=0;b<NumOfBase;b++) + { + + ProgressBar(b,NumOfBase); + + /////////////////////////////////////////////////////// + int index =0; + for(it = fMapName.begin() ; it != fMapName.end() ; it++ ) + { + int Z = it->first.Z; + int A = it->first.A; + int I = it->first.I; + FreshCompo[index] = fActinideCompoInit[b].GetZAIIsotopicQuantity(ZAI(Z,A,I)); + + index++; + } + /////////////////////////////////////////////////////// + + for(int Tstep=0 ;Tstep<fNOfTimeStep[b];Tstep++ ) + { + Time=fTime[b][Tstep]; + k_inf=fkeff[b][Tstep]; + fOutT->Fill(); + } + } + ProgressBar(1,1); + + fOutFile->Write(); + delete fOutT; + fOutFile-> Close(); + delete fOutFile; + +} + +//-------------------------------------------------------------------------------------------------- +void CheckJob() +{ //LOAD THE LIST OF EvolutionData + + cout<<endl; + cout<<"â•â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â•®"<<endl; + cout<<" Scanning : "<<endl; + cout<< fEvolutionDataFolder <<endl; + cout<<" for EvolutionData (.dat files) "<<endl; + cout<<"╰───────────────────────────────────────────────╯"<<endl; + + string Command = "find "+ fEvolutionDataFolder + " -name \"*.dat\" > JOB.tmp"; + system(Command.c_str()); + + ifstream JOB("JOB.tmp"); + + if(JOB.peek() == std::ifstream::traits_type::eof()) // if file is empty + { cout << endl << "\033[31mERROR: No .dat found in folder : " << fEvolutionDataFolder << "\033[0m" << endl; + exit(1); + } + + if (JOB.is_open()) + { + while (!JOB.eof()) + { + string tmp; + getline(JOB,tmp); + JobName.push_back(tmp); + } + } JOB.close(); JobName.pop_back(); + + // Remove temporary files... + Command = "\\rm -f JOB.tmp"; + system(Command.c_str()); + random_shuffle(JobName.begin(), JobName.end()); + cout << "\033[32m Scan complete \033[0m" <<endl; +} + +//-------------------------------------------------------------------------------------------------- +void ReadAndFill(string jobname) +{ //Read a .dat file and fill XS maps and the fuel initial composition + + vector<double> vT; + vector<int> Z; + vector<int> A; + vector<int> I; + vector<double> Q; + + ifstream DecayDB(jobname.c_str()); // Open the File + if(!DecayDB) + { + cout << "\033[33m !!Warning!! !!!EvolutiveProduct!!! \n Can't open \"" << jobname << "\"\033[0m\n" << endl; + } + + string line; + int start = 0; + + getline(DecayDB, line); + + /******Getting Time vecotr ....******/ + if( StringLine::NextWord(line, start, ' ') != "time") + { + cout << "\033[31m!!Bad Trouble!! !!!EvolutiveProduct!!! Bad Database file : " << jobname << "\033[0m" << endl; + exit (1); + } + + while(start < (int)line.size()) + vT.push_back(atof(StringLine::NextWord(line, start, ' ').c_str())); + + fTime.push_back(vT); + + fNOfTimeStep.push_back(int(vT.size())); + + /****Getting Keff***/ + start = 0; + getline(DecayDB, line); + string tmp = StringLine::NextWord(line, start, ' '); + vector<double> vKeff; + if ( tmp == "keff" || tmp == "Keff" ) + { + while(start < (int)line.size()) + vKeff.push_back(atof(StringLine::NextWord(line, start, ' ').c_str())); + } + fkeff.push_back(vKeff); + + /****Getting Inventories***/ + getline(DecayDB, line); + do + { + start = 0; + int z; + string tmp2 = StringLine::NextWord(line, start, ' '); + if (tmp2 == "Inv") { + z = atoi(StringLine::NextWord(line, start, ' ').c_str()); + } + else z = atoi(tmp2.c_str()); + int a = atoi(StringLine::NextWord(line, start, ' ').c_str()); + int i = atoi(StringLine::NextWord(line, start, ' ').c_str()); + + if(a!=0 && z!=0) + { + + ZAI zaitmp(z, a, i); + Z.push_back(z); + A.push_back(a); + I.push_back(i); + if(!fIsAllNucleiAlreadyFill) + { + fAllNuclei.push_back(zaitmp); + } + + long double q = atof(StringLine::NextWord(line, start, ' ').c_str()); + Q.push_back(q); + + } + + getline(DecayDB, line); + start = 0; + tmp2 = StringLine::NextWord(line, start, ' '); + + if(line == "" || line == "CrossSection" || tmp2 == "XSFis" || tmp2 == "XSCap" || tmp2 == "XSn2n") break; + }while (!DecayDB.eof() ); + + if(fAllNuclei.size()!=0) + fIsAllNucleiAlreadyFill=true; + + DecayDB.close(); + + double N = 0; + for(int i=0; i < (int)Z.size()-2; i++) + { + if( Z[i]>89 ) + N += Q[i]; + } + + + IsotopicVector CompoBasei; + IsotopicVector CompoBaseiUnormalize; + + for(int i=0; i < (int)Z.size()-2; i++) + { + if(Z[i]>89) + { + ZAI zai = ZAI(Z[i], A[i], I[i]); + CompoBasei.IVquantity.insert(pair<ZAI,double>(zai,Q[i]/N)); + CompoBaseiUnormalize.IVquantity.insert(pair<ZAI,double>(zai,Q[i])); + } + } + + fActinideCompoInit.push_back(CompoBasei); + double MassOfThisFuel = cZAIMass.GetMass(CompoBaseiUnormalize); + //cout<<MassOfThisFuel<<endl; + fHMMass.push_back(MassOfThisFuel); + +GoodJobName.push_back(jobname); + +} +/*------------------------------------------------------------------------------------------------- +COMPILATION : + +g++ -o Generate_MLP_Kinf Generate_MLP_Kinf.cxx `root-config --cflags` `root-config --libs` + + +*/ diff --git a/Utils/EQM/MLP_Kinf/Train_MLP.cxx b/Utils/EQM/MLP_Kinf/Train.cxx similarity index 58% rename from Utils/EQM/MLP_Kinf/Train_MLP.cxx rename to Utils/EQM/MLP_Kinf/Train.cxx index 8f8aa47e89c41e7537a55b31205f1e1794cd64ba..870f31787d920efe5c688ddd3488ceda47084f31 100755 --- a/Utils/EQM/MLP_Kinf/Train_MLP.cxx +++ b/Utils/EQM/MLP_Kinf/Train.cxx @@ -14,7 +14,6 @@ #include "TSystem.h" #include "TROOT.h" -#include "TMVARegGui.C" #if not defined(__CINT__) || defined(__MAKECINT__) #include "TMVA/Tools.h" @@ -25,23 +24,13 @@ using namespace TMVA; int main(int argc, char const *argv[]) { - if(argc!=2) - { - std::cout << "TrainMLP Usage :" << std::endl; - std::cout << "\tTrainMLP YourTrainingData.root" << std::endl; - } + //--------------------------------------------------------------- // This loads the library TMVA::Tools::Instance(); // --------------------------------------------------------------- - // if(argc !=3) - // { - // cout<<"error : "<<endl; - // cout<<"Usage : Train_MLP rootfile.root targetname : "<<endl; - // cout<<"\t targetname : keff or k_0 or k_1 ..."<<endl; - // exit(1); - // } - std::string TargetName = "k_inf";//argv[2]; + + std::string TargetName = "k_inf"; std::cout << std::endl; @@ -49,7 +38,7 @@ int main(int argc, char const *argv[]) // Create a new root output file - TString outfileName( "TMVA_"+TargetName+".root" ); + TString outfileName( "Training_output_"+TargetName+".root" ); TFile* outputFile = TFile::Open( outfileName, "RECREATE" );//UPDATE @@ -63,38 +52,10 @@ int main(int argc, char const *argv[]) TMVA::Factory *factory = new TMVA::Factory( "TMVARegression", outputFile, "!V:!Silent:Color:DrawProgressBar" ); - // If you wish to modify default settings - // (please check "src/Config.h" to see all available global options) - // (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0; - // (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory"; - - // Define the input variables that shall be used for the TMVA training - // note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)" - // [all types of expressions that can also be parsed by TTree::Draw( "expression" )] - - //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@// - //@@@Change/add variables if needed - //@@@ the variable name are the one you use in GenerateRootFile.cxx - //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@// - factory->AddVariable( "U8" , "U 238 " , "FractionIsotopic", 'F' ); - factory->AddVariable( "U5" , "U 235 " , "FractionIsotopic", 'F' ); - factory->AddVariable( "Pu8" , "Pu 238 " , "FractionIsotopic", 'F' ); - factory->AddVariable( "Pu9" , "Pu 239 " , "FractionIsotopic", 'F' ); - factory->AddVariable( "Pu10" , "Pu 240 " , "FractionIsotopic", 'F' ); - factory->AddVariable( "Pu11" , "Pu 241 " , "FractionIsotopic", 'F' ); - factory->AddVariable( "Pu12" , "Pu 242 " , "FractionIsotopic", 'F' ); - factory->AddVariable( "Am1" , "Am 241 " , "FractionIsotopic", 'F' ); - factory->AddVariable( "Time" , "Time" , "temps(s)", 'F' ); - - - // You can add so-called "Spectator variables", which are not used in the MVA training, - // but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the - // input variables, the response values of all trained MVAs, and the spectator variables - //factory->AddSpectator( "spec1:=var1*2", "Spectator 1", "units", 'F' ); - //factory->AddSpectator( "spec2:=var1*3", "Spectator 2", "units", 'F' ); - // Add the variable carrying the regression target + #include "_tmp/include_Train/InputVariables.cxx" + // Add the variable carrying the regression target factory->AddTarget(TargetName); // It is also possible to declare additional targets for multi-dimensional regression, ie: @@ -104,7 +65,7 @@ int main(int argc, char const *argv[]) // Read training and test data (see TMVAClassification for reading ASCII files) // load the signal and background event samples from ROOT trees TFile *input(0); - TString fname = argv[1]; //Training Data input file + TString fname = "_tmp/include_Train/TrainingInput.root"; //Training Data input file if (!gSystem->AccessPathName( fname )) input = TFile::Open( fname ); // check if file in local directory exists @@ -131,6 +92,14 @@ int main(int argc, char const *argv[]) // Apply additional cuts on the signal and background samples (can be different) TCut mycut = ""; // for example: TCut mycut = "abs(var1)<0.5 && abs(var2-0.5)<1"; + Long64_t NEvents = regTree->GetEntries(); + Long64_t NTraining = PropTraining * NEvents ; + Long64_t NTesting = NEvents - NTraining ; + + std::stringstream Samples_Parameters ; + Samples_Parameters << "nTrain_Regression=" << NTraining <<":"<< "nTest_Regression=" << NTesting <<":SplitMode=Random:NormMode=NumEvents:!V"; + + // tell the factory to use all remaining events in the trees after training for testing: factory->PrepareTrainingAndTestTree( mycut, "nTrain_Regression=0:nTest_Regression=0:SplitMode=Random:NormMode=NumEvents:!V" ); @@ -140,12 +109,17 @@ int main(int argc, char const *argv[]) // ---- Book MVA methods // + TString NType = "sigmoid"; + TString Arch = "18,21,9"; + TString Sampl = "0.5"; + TString LearRate = "0.1"; + + TString ParamNN = "!H:V:VarTransform=Norm:NeuronType=" + NType + ":NCycles=16000:HiddenLayers=" + Arch + ":TestRate=6:TrainingMethod=BFGS:LearningRate=" + LearRate + ":Sampling=" + Sampl + ":SamplingEpoch=0.8:ConvergenceImprove=1e-6:ConvergenceTests=15:!UseRegulator"; + std::stringstream Name; - Name<<"MLP_"<<TargetName; + Name<<"MLP_"<<TargetName; // Neural network (MLP) - factory->BookMethod( TMVA::Types::kMLP, Name.str().c_str(), "!H:V:VarTransform=Norm:NeuronType=tanh:NCycles=16000:HiddenLayers=8,:TestRate=6:TrainingMethod=BFGS:Sampling=0.3:SamplingEpoch=0.8:ConvergenceImprove=1e-6:ConvergenceTests=15:!UseRegulator" ); - - + factory->BookMethod( TMVA::Types::kMLP, Name.str().c_str(), ParamNN ); // -------------------------------------------------------------------------------------------------- // ---- Now you can tell the factory to train, test, and evaluate the MVAs @@ -169,10 +143,9 @@ int main(int argc, char const *argv[]) delete factory; - // Launch the GUI for the root macros -if (!gROOT->IsBatch()) TMVARegGui( outfileName ); + } /* -g++ -o Train_MLP `root-config --cflags` Train_MLP.cxx `root-config --glibs` -lTMVA -I$ROOTSYS/tmva/test/ +g++ -o Train `root-config --cflags` Train.cxx `root-config --glibs` -lTMVA -I$ROOTSYS/tmva/test/ */ \ No newline at end of file diff --git a/Utils/EQM/MLP_Kinf/include/Generate_MLP_Kinf.hxx b/Utils/EQM/MLP_Kinf/include/Generate_MLP_Kinf.hxx new file mode 100644 index 0000000000000000000000000000000000000000..a09faa60d9b4cb550255e32e1cbba2b59a0a7cf7 --- /dev/null +++ b/Utils/EQM/MLP_Kinf/include/Generate_MLP_Kinf.hxx @@ -0,0 +1,71 @@ +#include "ZAI.hxx" +#include <TGraph.h> +#include <TGraph.h> + +#include <vector> +#include <stdio.h> +#include <stdlib.h> +#include <iostream> +#include <fstream> +#include <sstream> +#include <string> +#include <sstream> +#include <cmath> +#include <map> +#include <iostream> +#include <iomanip> + +using namespace std; + +string dtoa(double num) +{ + ostringstream os(ostringstream::out); + os<<setprecision(3)<<num; + return os.str(); +} + +string FilePath; +string DataPath; + +vector<string> JobName; +vector<string> GoodJobName; + +vector< vector<double> > fTime; //Time vector of each depletion calculation (second) +vector<ZAI> fAllNuclei; //All the nuclei present in the fuel + +vector< vector<double> > fkeff; //Keff evolution of all Evolution Datas + + +vector<IsotopicVector> fActinideCompoInit; //Fresh fuel composition in atomic prop. + +vector<double> fHMMass; //Vector of initial Heavy metal mass (every element should be egual or very very close !!) + +vector<int> fNOfTimeStep; //number of time step in each Evolution data + +string fEvolutionDataFolder = ""; + +map<ZAI,string> fMapName; // List of ZAI and their name to consider for model parametrization (must of the time Fuel composition @ t=0) + +string fReactorType,fFuelType; + +vector <ZAIStreamList> fStreamList; // Fisisle or Fertile and default proportions for all nuclei in fresh fuel + +bool fIsAllNucleiAlreadyFill=false; + +void CheckJob(); +void ReadAndFill(string jobname); +void DumpForTestingNeuron(string filename); +void DumpInputNeuron(string filename); +void FillMapName(); +bool UserSayYes(); +string CreateInfoFile(); +void ReadInfo(string InfoDBFile,string &ReactorType,string &FuelType,double &Power); +void ProgressBar(double loopindex, double totalindex); +vector<double> GetAllCompoOf(ZAI zai); + +bool is_file_exist(const char *fileName); +void CompileTraining(); + +/* PRINT INFO */ +void Generate_tmva_factory_input(double ProportionOfTraining); + diff --git a/Utils/EQM/MLP_Kinf/include/StringLine.hxx b/Utils/EQM/MLP_Kinf/include/StringLine.hxx deleted file mode 100755 index da8500370b840d6abebf1360b3593151b6dab9d7..0000000000000000000000000000000000000000 --- a/Utils/EQM/MLP_Kinf/include/StringLine.hxx +++ /dev/null @@ -1,275 +0,0 @@ -#ifndef _STRINGLINE_ -#define _STRINGLINE_ - -#include <string> -#include <sstream> -#include <iostream> -#include <algorithm> -#include <cctype> -using namespace std; -/*! - \file - \brief Header file for StingLine class. -*/ - -// Class extracting fields from a string / line. -/*! - The aim of this class is to provide tools to extract fields ("word") from - a string and convert a string in Upper/Lower case. - All methods are static so that it is not necessary to create object to use them - - example: - \code - string line="The temperature is : 300.6 K"; - int start; - - 1st method: creation of StringLine - - start=0; - StringLine SL; - string the=SL.NextWord(line,start); - string temperature_is=SL.NextWord(line,start,':'); - string colon=SL.NextWord(line,start); - double T=atof(SL.NextWord(line,start).c_str()); - cout<<the<<endl<<temperature_is<<endl<<T<<endl; - - 2nd method: "using" the static methods - - start=0; - the=StringLine::NextWord(line,start); - temperature_is=StringLine::NextWord(line,start,':'); - colon=StringLine::NextWord(line,start); - T=atof(StringLine::NextWord(line,start).c_str()); - cout<<the<<endl<<temperature_is<<endl<<T<<endl; - \endcode - @author PTO - @version 0.1 -*/ - -class StringLine -{ - public: - // Find the next word in a line. - /*! - Find Next word in a line starting from position "start" in the line. If an alternative - separator is given, the word length is defined by the first position of sep or alt_sep found. - The first value of start is in general 0 (i.e. the beginning of the Line) - \param Line : a line containing words - \param start : from where to start to find the begining of a word - \param sep : the separator between 2 words (default=space) - \param alt_sep : the alternative separator between 2 words (default='') - */ - static string NextWord(string Line,int &start,char sep=' ', char alt_sep='\0'); - // Find the previous word in a line. - /*! - Find Previous word in a line starting from position "start" in the line. If an alternative - separator is given, the word length is defined by the first position of sep or alt_sep found. - The first value of start is in general the end of the Line. - \param Line : a line containing words - \param start : from where to start to find the begining of a word - \param sep : the separator between 2 words (default=space) - \param alt_sep : the alternative separator between 2 words (default='') - */ - static string PreviousWord(string Line,int &start,char sep=' ', char alt_sep='\0'); - static void ToLower(string &Line); // convert a string to Lower case - static void ToUpper(string &Line); // convert a string to Upper case - - // Find \p search in \p Line from the begining. - /*! - returns the position, starting from the begenning of the first occurence - of \p search in \p Line if it is found, else returns -1 - \param search : a string to find - \param Line : where to search - */ - static int Find(const char *search,string Line); - // Find \p search in \p Line from the end. - /*! - returns the position, starting from the end of the first occurence - of \p search in \p Line if it is found, else returns -1 - \param search : a string to find - \param Line : where to search - */ - static int rFind(const char *search,string Line); - // convert a input type (\p in_T) to another (\p out_T). - /*! - Example: - \code - string s="32.12"; - double t=StringLine::convert<double>(s); - string temperature=StringLine::convert<string>(300.); - \endcode - \param t : the input value - */ - template <class out_T, class in_T> static out_T convert(const in_T & t); - // Find the start of a word in a line. - /*! - \param Line : a line containing words - \param CurrentPosition : from where to start to find the begining of a word - \param sep : the separator between 2 words (default=space) - \param alt_sep : the alternative separator between 2 words (default='') - */ - static int GetStartWord(string Line,int CurrentPosition,char sep=' ', char alt_sep='\0'); - // Find the end of a word in a line. - /*! - \param Line : a line containing words - \param CurrentPosition : from where to start to find the end of a word - \param sep : the separator between 2 words (default=space) - \param alt_sep : the alternative separator between 2 words (default='') - */ - static int GetEndWord(string Line,int CurrentPosition,char sep=' ', char alt_sep='\0'); - // Replace a sub-string by an other in a string. - /*! - \param InLine : the string which contains the sub-string to replace - \param ToReplace : the sub-string to replace - \param By : the sub-string ToReplace is replaced by the sub-string By in Inline - */ - string ReplaceAll(string InLine, string ToReplace, string By); -}; - - -//_________________________________________________________________________________ -inline string StringLine::NextWord(string Line,int &start,char sep, char alt_sep) -{ - string Word=""; - if(start>=int(Line.size())) - { - return Word; - } - start=GetStartWord(Line,start,sep,alt_sep); - int wordlength=GetEndWord(Line,start,sep,alt_sep)-start; - - Word=Line.substr(start,wordlength); - - start+=wordlength; - return Word; -} -//_________________________________________________________________________________ -inline string StringLine::PreviousWord(string Line,int &start,char sep, char alt_sep) -{ - string Word=""; - if(start<=0) - { - return Word; - } - int pos=Line.rfind(sep,start); - int alt_pos=-1; - int real_pos=pos; - char real_sep=sep; - if(alt_sep!='\0') - { - alt_pos=Line.rfind(alt_sep,start); - real_pos=max(pos,alt_pos); - if(real_pos!=pos) - real_sep=alt_sep; - } - int wordlength=start-Line.rfind(real_sep,real_pos); - if(real_pos<=0) - { - Word=Line.substr(0,start+1); - start=0; - return Word; - } - Word=Line.substr(real_pos+1,wordlength); - - start-=wordlength+1; - return Word; -} - -//_________________________________________________________________________________ -inline void StringLine::ToLower(string &Line) -{ - transform (Line.begin(), Line.end(), // source - Line.begin(), // destination - (int(*)(int))tolower); // operation -} - -//_________________________________________________________________________________ -inline void StringLine::ToUpper(string &Line) -{ - transform (Line.begin(), Line.end(), // source - Line.begin(), // destination - (int(*)(int))toupper); // operation -} - -//_________________________________________________________________________________ -inline int StringLine::GetStartWord(string Line,int CurrentPosition,char sep, char alt_sep) -{ - int pos=Line.find(sep,CurrentPosition); - int alt_pos=-1; - if(alt_sep!='\0') - alt_pos=Line.find(alt_sep,CurrentPosition); - int real_pos=pos; - char real_sep=sep; - if(alt_pos>=0) - { - real_pos=min(pos,alt_pos); - if(pos==int(string::npos))real_pos=alt_pos; - if(real_pos!=pos) - real_sep=alt_sep; - } - if(real_pos==int(string::npos)) return CurrentPosition; - while(CurrentPosition<int(Line.size()) && Line[CurrentPosition]==real_sep) - CurrentPosition++; - return CurrentPosition; -} - -//_________________________________________________________________________________ -inline int StringLine::GetEndWord(string Line,int CurrentPosition,char sep, char alt_sep) -{ - int pos=Line.find(sep,CurrentPosition); - int alt_pos=-1; - if(alt_sep!='\0') - alt_pos=Line.find(alt_sep,CurrentPosition); - int real_pos=pos; - if(alt_pos>=0) - { - real_pos=min(pos,alt_pos); - if(pos==int(string::npos))real_pos=alt_pos; - } - if(real_pos==int(string::npos)) - return Line.size(); - return real_pos; -} - -//_________________________________________________________________________________ -inline int StringLine::Find(const char *search,string Line) -{ - size_t Pos=Line.find(search); - if(Pos != string::npos ) return Pos; - return -1; -} - -//_________________________________________________________________________________ -inline int StringLine::rFind(const char *search,string Line) -{ - size_t Pos=Line.rfind(search); - if(Pos != string::npos) return Pos; - return -1; -} - -//_________________________________________________________________________________ -template <class out_T, class in_T> -inline out_T StringLine::convert(const in_T & t) -{ - stringstream stream; - stream << t; // insert value to stream - out_T result; // store conversion's result here - stream >> result; // write value to result - return result; -} - -//_________________________________________________________________________________ -inline string StringLine::ReplaceAll(string InLine, string ToReplace, string By) -{ - int start=0; - int pos=InLine.find(ToReplace,start); - while(pos!=int(string::npos)) - { - InLine.replace(pos,ToReplace.size(),By); - start=0; - pos=InLine.find(ToReplace,start); - } - return InLine; - -} -#endif