bool CloseTable () { if ( StreamData.is_open() ) StreamData.close(); if ( StreamIndex.is_open() ) StreamData.close(); return true; }
void Noggin::stopLocLog() { outputFile.close(); loggingLoc = false; }
void citire() { f.getline(s,LgMax); lg=strlen(s); f.close(); }
bool KMeansQuantizer::loadModelFromFile(fstream &file){ initialized = false; numClusters = 0; clusters.clear(); quantizationDistances.clear(); if( !file.is_open() ){ errorLog << "loadModelFromFile(fstream &file) - The file is not open!" << endl; return false; } string word; //First, you should read and validate the header file >> word; if( word != "KMEANS_QUANTIZER_FILE_V1.0" ){ errorLog << "loadModelFromFile(fstream &file) - Invalid file format!" << endl; return false; } //Second, you should load the base feature extraction settings to the file if( !loadFeatureExtractionSettingsFromFile( file ) ){ errorLog << "loadFeatureExtractionSettingsFromFile(fstream &file) - Failed to load base feature extraction settings from file!" << endl; return false; } file >> word; if( word != "QuantizerTrained:" ){ errorLog << "loadModelFromFile(fstream &file) - Failed to load QuantizerTrained!" << endl; return false; } file >> trained; file >> word; if( word != "NumClusters:" ){ errorLog << "loadModelFromFile(fstream &file) - Failed to load NumClusters!" << endl; return false; } file >> numClusters; if( trained ){ clusters.resize(numClusters, numInputDimensions); file >> word; if( word != "Clusters:" ){ errorLog << "loadModelFromFile(fstream &file) - Failed to load Clusters!" << endl; return false; } for(UINT k=0; k<numClusters; k++){ for(UINT j=0; j<numInputDimensions; j++){ file >> clusters[k][j]; } } initialized = true; featureDataReady = false; quantizationDistances.resize(numClusters,0); } return true; }
bool Classifier::loadBaseSettingsFromFile(fstream &file){ if( !file.is_open() ){ errorLog << "loadBaseSettingsFromFile(fstream &file) - The file is not open!" << endl; return false; } //Try and load the base settings from the file if( !MLBase::loadBaseSettingsFromFile( file ) ){ return false; } string word; //Load if the number of clusters file >> word; if( word != "UseNullRejection:" ){ errorLog << "loadBaseSettingsFromFile(fstream &file) - Failed to read UseNullRejection header!" << endl; clear(); return false; } file >> useNullRejection; //Load if the classifier mode file >> word; if( word != "ClassifierMode:" ){ errorLog << "loadBaseSettingsFromFile(fstream &file) - Failed to read ClassifierMode header!" << endl; clear(); return false; } file >> classifierMode; //Load if the null rejection coeff file >> word; if( word != "NullRejectionCoeff:" ){ errorLog << "loadBaseSettingsFromFile(fstream &file) - Failed to read NullRejectionCoeff header!" << endl; clear(); return false; } file >> nullRejectionCoeff; //If the model is trained then load the model settings if( trained ){ //Load the number of classes file >> word; if( word != "NumClasses:" ){ errorLog << "loadBaseSettingsFromFile(fstream &file) - Failed to read NumClasses header!" << endl; clear(); return false; } file >> numClasses; //Load the null rejection thresholds file >> word; if( word != "NullRejectionThresholds:" ){ errorLog << "loadBaseSettingsFromFile(fstream &file) - Failed to read NullRejectionThresholds header!" << endl; clear(); return false; } nullRejectionThresholds.resize(numClasses); for(UINT i=0; i<nullRejectionThresholds.size(); i++){ file >> nullRejectionThresholds[i]; } //Load the class labels file >> word; if( word != "ClassLabels:" ){ errorLog << "loadBaseSettingsFromFile(fstream &file) - Failed to read ClassLabels header!" << endl; clear(); return false; } classLabels.resize( numClasses ); for(UINT i=0; i<classLabels.size(); i++){ file >> classLabels[i]; } if( useScaling ){ //Load if the Ranges file >> word; if( word != "Ranges:" ){ errorLog << "loadBaseSettingsFromFile(fstream &file) - Failed to read Ranges header!" << endl; clear(); return false; } ranges.resize(numInputDimensions); for(UINT i=0; i<ranges.size(); i++){ file >> ranges[i].minValue; file >> ranges[i].maxValue; } } } return true; }
bool DecisionStump::loadModelFromFile(fstream &file){ if(!file.is_open()) { errorLog <<"loadModelFromFile(fstream &file) - The file is not open!" << endl; return false; } string word; file >> word; if( word != "WeakClassifierType:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read WeakClassifierType header!" << endl; return false; } file >> word; if( word != weakClassifierType ){ errorLog <<"loadModelFromFile(fstream &file) - The weakClassifierType:" << word << " does not match: " << weakClassifierType << endl; return false; } file >> word; if( word != "Trained:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read Trained header!" << endl; return false; } file >> trained; file >> word; if( word != "NumInputDimensions:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read NumInputDimensions header!" << endl; return false; } file >> numInputDimensions; file >> word; if( word != "DecisionFeatureIndex:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read DecisionFeatureIndex header!" << endl; return false; } file >> decisionFeatureIndex; file >> word; if( word != "Direction:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read Direction header!" << endl; return false; } file >> direction; file >> word; if( word != "NumSteps:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read NumSteps header!" << endl; return false; } file >> numSteps; file >> word; if( word != "DecisionValue:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read DecisionValue header!" << endl; return false; } file >> decisionValue; //We don't need to close the file as the function that called this function should handle that return true; }
void create() { f.open(fname, ios::out); f.close(); cout<<"File named "<<fname<<" created.\n\n"; }
//********************************************************************* // FUNCTION: OpenInputFile // DESCRIPTION: Open the input text file. // INPUT: // Parameters: // std::string filename - Path to the input file. // std::fstream file - The file object to use when opening the // input file. // OUTPUT: // Return Val: Boolean indicating success of the file open // operation. // Parameters: // std::fstream file - Initialized with the input file open on // success. // PERFORMANCE: f(n) = k //********************************************************************** bool OpenInputFile(string filename, fstream& file) { file.open(filename.c_str(), fstream::in); return(file.good()); } // OpenInputFile
std::ifstream::pos_type filesize(fstream &in) { in.seekg(0, std::ifstream::end); return in.tellg(); }
bool LogisticRegression::loadLegacyModelFromFile( fstream &file ){ string word; file >> word; if(word != "NumFeatures:"){ errorLog << "loadLegacyModelFromFile( fstream &file ) - Could not find NumFeatures!" << endl; return false; } file >> numInputDimensions; file >> word; if(word != "NumOutputDimensions:"){ errorLog << "loadLegacyModelFromFile( fstream &file ) - Could not find NumOutputDimensions!" << endl; return false; } file >> numOutputDimensions; file >> word; if(word != "UseScaling:"){ errorLog << "loadLegacyModelFromFile( fstream &file ) - Could not find UseScaling!" << endl; return false; } file >> useScaling; ///Read the ranges if needed if( useScaling ){ //Resize the ranges buffer inputVectorRanges.resize(numInputDimensions); targetVectorRanges.resize(numOutputDimensions); //Load the ranges file >> word; if(word != "InputVectorRanges:"){ file.close(); errorLog << "loadLegacyModelFromFile( fstream &file ) - Failed to find InputVectorRanges!" << endl; return false; } for(UINT j=0; j<inputVectorRanges.size(); j++){ file >> inputVectorRanges[j].minValue; file >> inputVectorRanges[j].maxValue; } file >> word; if(word != "OutputVectorRanges:"){ file.close(); errorLog << "loadLegacyModelFromFile( fstream &file ) - Failed to find OutputVectorRanges!" << endl; return false; } for(UINT j=0; j<targetVectorRanges.size(); j++){ file >> targetVectorRanges[j].minValue; file >> targetVectorRanges[j].maxValue; } } //Resize the weights w.resize(numInputDimensions); //Load the weights file >> word; if(word != "Weights:"){ errorLog << "loadLegacyModelFromFile( fstream &file ) - Could not find the Weights!" << endl; return false; } file >> w0; for(UINT j=0; j<numInputDimensions; j++){ file >> w[j]; } //Resize the regression data vector regressionData.resize(1,0); //Flag that the model has been trained trained = true; return true; }
void init() { if (ifstream ("Pontuacao.bin")) { arquivoPontuacao.open ("Pontuacao.bin", ios::in | ios::binary); arquivoPontuacao >> pontuacaoMaisAlta; arquivoPontuacao.close(); }
int main( int argc, char **argv ) { if ( argc < 2 ) { cout << "something wrong" << endl; exit(1); } else { read_parameters(argc,argv); } Timer initialization_timer; rnd = new Random((unsigned) time(&t)); graph = new UndirectedGraph(i_file); init_pheromone_trail(); register int i = 0; register int j = 0; register int k = 0; register int b = 0; cout << endl; for (int card_counter = cardb; card_counter <= carde; card_counter++) { cardinality = card_counter; if ((cardinality == cardb) || (cardinality == carde) || ((cardinality % cardmod) == 0)) { printf("begin cardinality %d\n",cardinality); if (tfile_is_given) { if (times.count(cardinality) == 1) { time_limit = times[cardinality]; } } vector<double> results; vector<double> times_best_found; double biar = 0.0; int n_of_ants = (int)(((double)((*graph).edges).size()) / ((double)cardinality)); if (n_of_ants < 15) { n_of_ants = 15; } if (n_of_ants > 50) { n_of_ants = 50; } if (ants.size() > 0) { for (list<KCT_Ant*>::iterator anAnt = ants.begin(); anAnt != ants.end(); anAnt++) { delete(*anAnt); } } ants.clear(); for (i = 0; i < n_of_ants; i++) { KCT_Ant* ant = new KCT_Ant(); ant->initialize(graph,rnd,pheromone,daemon_action); ants.push_back(ant); } for (int trial_counter = 1; trial_counter <= n_of_trials; trial_counter++) { printf("begin try %d\n",trial_counter); UndirectedGraph* best = NULL; UndirectedGraph* newSol = NULL; UndirectedGraph* restartBest = NULL; double ib_weight = 0.0; double rb_weight = 0.0; double gb_weight = 0.0; Timer timer; if ((!(card_counter == cardb)) || (!(trial_counter == 1))) { reset_pheromone_trail(); for (list<KCT_Ant*>::iterator ant = ants.begin(); ant != ants.end(); ant++) { (*ant)->restart_reset(); } } int iter = 1; double cf = 0.0; bool restart = false; bool program_stop = false; bool bs_update = false; while (program_stop == false) { for (list<KCT_Ant*>::iterator ant = ants.begin(); ant != ants.end(); ant++) { for (k = 0; k < cardinality; k++) { (*ant)->step(0.8); } (*ant)->evaluate(); } if (!(newSol == NULL)) { delete(newSol); } if (elite_action == "no") { newSol = getBestDaemonSolutionInIteration(); } else { KCT_Ant* bestAnt = getBestDaemonAntInIteration(); bestAnt->eliteAction(); newSol = new UndirectedGraph(); newSol->copy(bestAnt->getCurrentDaemonSolution()); } if (iter == 1) { best = new UndirectedGraph(); printf("best %f\ttime %f\n",newSol->weight(),timer.elapsed_time(Timer::VIRTUAL)); best->copy(newSol); restartBest = new UndirectedGraph(newSol); results.push_back(newSol->weight()); times_best_found.push_back(timer.elapsed_time(Timer::VIRTUAL)); if (trial_counter == 1) { biar = newSol->weight(); } else { if (newSol->weight() < biar) { biar = newSol->weight(); } } } else { if (restart) { restart = false; restartBest->copy(newSol); if (newSol->weight() < best->weight()) { printf("best %f\ttime %f\n",newSol->weight(),timer.elapsed_time(Timer::VIRTUAL)); best->copy(newSol); results[trial_counter-1] = newSol->weight(); times_best_found[trial_counter-1] = timer.elapsed_time(Timer::VIRTUAL); if (newSol->weight() < biar) { biar = newSol->weight(); } } } else { if (newSol->weight() < restartBest->weight()) { restartBest->copy(newSol); } if (newSol->weight() < best->weight()) { printf("best %f\ttime %f\n",newSol->weight(),timer.elapsed_time(Timer::VIRTUAL)); best->copy(newSol); results[trial_counter-1] = newSol->weight(); times_best_found[trial_counter-1] = timer.elapsed_time(Timer::VIRTUAL); if (newSol->weight() < biar) { biar = newSol->weight(); } } } } cf = get_cf(newSol); //cout << "cf: " << cf << endl; if (bs_update && (cf > 0.99)) { //cout << "doing restart" << endl; bs_update = false; restart = true; cf = 0.0; reset_pheromone_trail(); } else { if (cf > 0.99) { bs_update = true; } if (!bs_update) { if (cf < 0.7) { l_rate = 0.15; ib_weight = 2.0/3.0; rb_weight = 1.0/3.0; gb_weight = 0.0; } if ((cf >= 0.7) && (cf < 0.95)) { l_rate = 0.1; ib_weight = 1.0 / 3.0; rb_weight = 2.0 / 3.0; gb_weight = 0.0; } if (cf >= 0.95) { l_rate = 0.05; ib_weight = 0.0; rb_weight = 1.0; gb_weight = 0.0; } } else { // if bs_update = TRUE we use the best_so_far solution for updating the pheromone values l_rate = 0.1; ib_weight = 0.0; rb_weight = 0.0; gb_weight = 1.0; } map<Edge*,double>* trans_best = translate_solution(best); map<Edge*,double>* trans_newSol = translate_solution(newSol); map<Edge*,double>* trans_restartBest = translate_solution(restartBest); map<Edge*,double>* new_pd = new map<Edge*,double>; for (list<Edge*>::iterator e = (graph->edges).begin(); e != (graph->edges).end(); e++) { (*new_pd)[*e] = 0.0; (*new_pd)[*e] = (*new_pd)[*e] + (ib_weight * (*trans_newSol)[*e]) + (rb_weight * (*trans_restartBest)[*e]) + (gb_weight * (*trans_best)[*e]); } for (list<Edge*>::iterator e = (graph->edges).begin(); e != (graph->edges).end(); e++) { (*pheromone)[*e] = (*pheromone)[*e] + (l_rate * ((*new_pd)[*e] - (*pheromone)[*e])); if ((*pheromone)[*e] > tau_max) { (*pheromone)[*e] = tau_max; } if ((*pheromone)[*e] < tau_min) { (*pheromone)[*e] = tau_min; } } delete(trans_best); delete(trans_newSol); delete(trans_restartBest); delete(new_pd); } for (list<KCT_Ant*>::iterator i = ants.begin(); i != ants.end(); i++) { (*i)->reset(); } iter = iter + 1; if (tfile_is_given) { if (timer.elapsed_time(Timer::VIRTUAL) > time_limit) { program_stop = true; } } else { if (time_limit_given && iter_limit_given) { if ((timer.elapsed_time(Timer::VIRTUAL) > time_limit) || (iter > n_of_iter)) { program_stop = true; } } else { if (time_limit_given) { if (timer.elapsed_time(Timer::VIRTUAL) > time_limit) { program_stop = true; } } else { if (iter > n_of_iter) { program_stop = true; } } } } } printf("end try %d\n",trial_counter); // eturetken 18.09.09. Write the best MST for this cardinality to the file. //////////////////////////////////////////////////////////////////// if( mstfile_is_given ) { string MSTFile(mst_file); best->Write2File(concatIntToString(MSTFile, card_counter) + ".mst"); } //////////////////////////////////////////////////////////////////// delete(best); delete(restartBest); delete(newSol); } double r_mean = 0.0; double t_mean = 0.0; for (int i = 0; i < results.size(); i++) { r_mean = r_mean + results[i]; t_mean = t_mean + times_best_found[i]; } r_mean = r_mean / ((double)results.size()); t_mean = t_mean / ((double)times_best_found.size()); double rsd = 0.0; double tsd = 0.0; for (int i = 0; i < results.size(); i++) { rsd = rsd + pow(results[i]-r_mean,2.0); tsd = tsd + pow(times_best_found[i]-t_mean,2.0); } rsd = rsd / ((double)(results.size()-1.0)); if (rsd > 0.0) { rsd = sqrt(rsd); } tsd = tsd / ((double)(times_best_found.size()-1.0)); if (tsd > 0.0) { tsd = sqrt(tsd); } if (output_file_given == true) { fout << cardinality << "\t" << r_mean << "\t" << rsd << "\t" << t_mean << "\t" << tsd << endl; } else { printf("statistics\t%d\t%g\t%f\t%f\t%f\t%f\n",cardinality,biar,r_mean,rsd,t_mean,tsd); } printf("end cardinality %d\n",cardinality); } } if (output_file_given == true) { fout.close(); } delete(graph); delete rnd; }
void read_parameters(int argc, char **argv) { int iarg=1; while (iarg < argc) { if (strcmp(argv[iarg],"-i")==0) { strcpy(i_file,argv[++iarg]); input_file_given = true; } else if (strcmp(argv[iarg],"-m")==0) { strcpy(mst_file,argv[++iarg]); mstfile_is_given = true; } else if (strcmp(argv[iarg],"-tfile")==0) { strcpy(tfile,argv[++iarg]); readTimesFile(); tfile_is_given = true; } else if (strcmp(argv[iarg],"-t")==0) { time_limit=atof(argv[++iarg]); time_limit_given = true; } else if (strcmp(argv[iarg],"-maxiter")==0) { n_of_iter=atoi(argv[++iarg]); iter_limit_given = true; } else if (strcmp(argv[iarg],"-n")==0) { n_of_trials=atoi(argv[++iarg]); } else if (strcmp(argv[iarg],"-o")==0) { strcpy(o_file,argv[++iarg]); output_file_given = true; } else if (strcmp(argv[iarg],"-output")==0) { if (strcmp(argv[++iarg],"det")==0) { output = "det"; } else { output = "min"; } } else if (strcmp(argv[iarg],"-eliteaction")==0) { if (strcmp(argv[++iarg],"yes")==0) { elite_action = "yes"; } else { elite_action = "no"; } } else if (strcmp(argv[iarg],"-ls")==0) { if (strcmp(argv[++iarg],"leafs")==0) { daemon_action = "leafs"; } else { if (strcmp(argv[iarg],"tsleafs")==0) { daemon_action = "tsleafs"; } else { daemon_action = "none"; } } } else if (strcmp(argv[iarg],"-nants")==0) { n_of_ants = atoi(argv[++iarg]); } else if (strcmp(argv[iarg],"-cardmod")==0) { cardmod = atoi(argv[++iarg]); } else if (strcmp(argv[iarg],"-lrate")==0) { l_rate = atof(argv[++iarg]); } else if (strcmp(argv[iarg],"-cardb")==0) { cardb=atoi(argv[++iarg]); cardb_is_given = true; } else if (strcmp(argv[iarg],"-carde")==0) { carde=atoi(argv[++iarg]); carde_is_given = true; } iarg++; } if (input_file_given == false) { printf(CALL_MISSFILE_STR); printf("\n"); exit(1); } if (cardb_is_given == false) { printf(CALL_MISSCARD_STR); printf("\n"); exit(1); } else { if (carde_is_given == false) { carde = cardb; } } if ((time_limit_given == false) && (iter_limit_given == false) && (tfile_is_given == false)) { cout << endl; cout << "please specify:" << endl; cout << endl; cout << "* a time limit (i.e., -t 20.0), or" << endl; cout << "* an iteration limit (i.e., -maxiter 1000), or" << endl; cout << "* both" << endl; cout << endl; exit(1); } if (output_file_given == true) { fout.open(o_file,std::ios::out); if (!fout.is_open()) { cout << "Problems with writing to file. Using standard output." << endl; output_file_given = false; } } }
void readFile(fstream &file, bool isSequential) { int fd; uint64_t start, end; double average, total = 0, totalAverage = 0; const char* fileName; warmup(); double overhead = getReadOverhead(); void* buffer = malloc(BLOCK_SIZE); pid_t pids[TEST_FILE_NUMBER]; // using TEST_FILE_NUMBER as thread number for(int i = 1; i < TEST_FILE_NUMBER; i++) { file << "Company process number=" << i << "\n"; for(int j = 0; j < i; j++) { // fork new process pids[j] = fork(); if(pids[j] < 0) { cout << "Can't fork a new process" << endl; abort(); } else if(pids[j] == 0) { // enter the child process, do pure read process without any fetching data pureRead(1 + j, isSequential); exit(0); } } totalAverage = 0; // parent process finishing fetching performance data for (int j = 0; j < TEST_TIMES; j++) { fileName = (TEST_FILE_PREFIX + to_string(1)).c_str(); fd = open(fileName, O_SYNC | O_RDONLY); if(fd < 0) { cout << "Can't open the test file, please create a test file first: "<< fileName << endl; return; } // http://stackoverflow.com/questions/2299402/how-does-one-do-raw-io-on-mac-os-x-ie-equivalent-to-linuxs-o-direct-flag if(fcntl(fd, F_NOCACHE, 1) < 0) { cout << "Can't close cache of the test file" << endl; return; } // call purge to clear cache // system("purge"); total = 0; if(isSequential) { for(int k = 0; k < BLOCK_NUMBER; k++) { start = rdtscStart(); read(fd, buffer, BLOCK_SIZE); end = rdtscEnd(); total += (double) end - (double) start - overhead; } } else { off_t offset; for(int k = 0; k < BLOCK_NUMBER; k++) { start = rdtscStart(); offset = rand() % BLOCK_NUMBER; // using lseek to set offset lseek(fd, offset, SEEK_SET); read(fd, buffer, BLOCK_SIZE); end = rdtscEnd(); total += (double) end - (double) start - overhead; } } average = (total / BLOCK_NUMBER) * 0.37 / 1000000; file << average << "\n"; file.flush(); totalAverage += average; close(fd); } cout << "Company thread count = " << i << " average cycles = " << totalAverage / TEST_TIMES << endl; wait(NULL); } // close file and free memory free(buffer); }
bool AdaBoost::loadModelFromFile(fstream &file){ clear(); if(!file.is_open()) { errorLog << "loadModelFromFile(string filename) - Could not open file to load model!" << endl; return false; } std::string word; file >> word; //Check to see if we should load a legacy file if( word == "GRT_ADABOOST_MODEL_FILE_V1.0" ){ return loadLegacyModelFromFile( file ); } if( word != "GRT_ADABOOST_MODEL_FILE_V2.0" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read file header!" << endl; errorLog << word << endl; return false; } //Load the base settings from the file if( !Classifier::loadBaseSettingsFromFile(file) ){ errorLog << "loadModelFromFile(string filename) - Failed to load base settings from file!" << endl; return false; } file >> word; if( word != "PredictionMethod:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read PredictionMethod header!" << endl; return false; } file >> predictionMethod; if( trained ){ file >> word; if( word != "Models:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read Models header!" << endl; return false; } //Load the models models.resize( numClasses ); for(UINT i=0; i<models.size(); i++){ if( !models[i].loadModelFromFile( file ) ){ errorLog << "loadModelFromFile(fstream &file) - Failed to load model " << i << " from file!" << endl; file.close(); return false; } } //Recompute the null rejection thresholds recomputeNullRejectionThresholds(); //Resize the prediction results to make sure it is setup for realtime prediction maxLikelihood = DEFAULT_NULL_LIKELIHOOD_VALUE; bestDistance = DEFAULT_NULL_DISTANCE_VALUE; classLikelihoods.resize(numClasses,DEFAULT_NULL_LIKELIHOOD_VALUE); classDistances.resize(numClasses,DEFAULT_NULL_DISTANCE_VALUE); } return true; }
//void LMParser::parseCNFString(string formula,vector<PredicateSymbol*> predicateList) void LMParser::parseCNFString(string formula,fstream& filestr) { //apend multiple lines char* buf = new char[1024]; size_t pos; while(1) { pos = formula.find(WEIGHTSEPARATOR); if(pos!=string::npos) break; else { filestr.getline(buf,1024); string s(buf); s.erase( remove(s.begin(), s.end(), ' '), s.end() ); formula.append(s); } } delete[] buf; //extract the weight string weight = formula.substr(pos+2); stringstream convert(weight); double wt; convert >> wt; formula = formula.substr(0,pos); //cout<<wt<<endl; vector<string> clauseStrings; LStringConversionUtils::tokenize(formula,clauseStrings,ANDOPERATOR); vector<WClause*> CNF; for(int i=0;i<clauseStrings.size();i++) { //If clause starts with a paranthesis if(clauseStrings[i].find(LEFTPRNTH)==0) { //eliminate the first and last paranthesis clauseStrings[i] = clauseStrings[i].substr(1,clauseStrings[i].size()-2); } vector<string> atomStrings; LStringConversionUtils::tokenize(clauseStrings[i],atomStrings,OROPERATOR); vector<vector<string> > sTermsList(atomStrings.size()); //sign of an atom vector<bool> sign(atomStrings.size()); //index into the predicate symbols vector<int> predicateSymbolIndex(atomStrings.size()); for(int j=0;j<atomStrings.size();j++) { //find opening and closing braces int startpos=atomStrings[j].find(LEFTPRNTH); string predicateName = atomStrings[j].substr(0,startpos); if(predicateName.find(NOTOPERATOR)==0) { //negation predicateName = predicateName.substr(1,predicateName.size()); sign[j]=true; } for(int k=0;k<mln.symbols.size();k++) { //found the predicate if(mln.symbols[k]->symbol.compare(predicateName)==0) { predicateSymbolIndex[j] = k; break; } } int endpos=atomStrings[j].find(RIGHTPRNTH); string termsString = atomStrings[j].substr(startpos+1,endpos-startpos-1); vector<string> terms; LStringConversionUtils::tokenize(termsString,terms,COMMASEPARATOR); sTermsList[j]=terms; //check if the number of terms is equal to the declared predicate if(terms.size()!=mln.symbols[predicateSymbolIndex[j]]->variable_types.size()) { cout<<"Error! Number/domain of terms in the predicate delcaration does not match in formula::"<<predicateName.c_str()<<endl; exit(-1); } } //create required terms vector<vector<LvrTerm*> > iTermsList(atomStrings.size()); for(int j=0;j<atomStrings.size();j++) { //for each term of atom i, check if it has already appeared in previous atoms of clause vector<LvrTerm*> iTerms(sTermsList[j].size()); for(int k=0;k<sTermsList[j].size();k++) { int domainIndex = predicateDomainMap[predicateSymbolIndex[j]].at(k); //if term is a constant must be a unique term if(isTermConstant(sTermsList[j].at(k))) { //find the id of the term int id=-1; for(int m=0;m<domainList[domainIndex]->values.size();m++) { if(domainList[domainIndex]->values[m].compare(sTermsList[j].at(k))==0) { id=m; break; } } if(id==-1) { cout<<"Constant does not match predicate's domain::"<<domainList[domainIndex]->name<<endl; exit(-1); } iTerms[k] = new LvrTerm(0,id); } else { int domainSize = domainList[domainIndex]->values.size(); bool isExistingTerm = false; int atomIndex=-1; int termIndex=-1; //check in term lists for atoms 0 to j; for(int m=0;m<j;m++) { for(int n=0;n<sTermsList[m].size();n++) { if((sTermsList[m])[n].compare((sTermsList[j])[k])==0) { //check if the domains of the matched variables are the same int atomSymbolIndex1 = predicateSymbolIndex[m]; int atomId1 = mln.symbols[atomSymbolIndex1]->id; int domainListIndex1 = predicateDomainMap[atomId1].at(n); int atomSymbolIndex2 = predicateSymbolIndex[j]; int atomId2 = mln.symbols[atomSymbolIndex2]->id; int domainListIndex2 = predicateDomainMap[atomId2].at(k); if(domainList[domainListIndex1]->name.compare(domainList[domainListIndex2]->name)!=0) { cout<<"Error! variables do not match type ::"<<atomStrings[j]<<"("<<domainList[domainListIndex1]->name<<", "<<domainList[domainListIndex2]->name<<")"<<endl; exit(-1); } //variable is repeated, use the term created for atom m, term n isExistingTerm = true; atomIndex = m; termIndex = n; break; } } if(isExistingTerm) break; } if(isExistingTerm) { //use the terms created for previous atoms iTerms[k] = (iTermsList[atomIndex])[termIndex]; } else { //create a new LvrTerm iTerms[k] = create_new_term(domainSize); } } } iTermsList[j] = iTerms; }//j atoms WClause* newClause = create_new_clause(predicateSymbolIndex,sign,iTermsList); newClause->weight = LogDouble(wt,false); CNF.push_back(newClause); }//i clauses int formulaStartIndex = mln.clauses.size(); for(int i=0;i<CNF.size();i++) { mln.clauses.push_back(CNF[i]); } int formulaEndIndex = mln.clauses.size(); mln.formulas.push_back(new Formula(formulaStartIndex,formulaEndIndex,LogDouble(wt,false))); }
bool AdaBoost::loadLegacyModelFromFile( fstream &file ){ string word; file >> word; if( word != "NumFeatures:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read NumFeatures header!" << endl; return false; } file >> numInputDimensions; file >> word; if( word != "NumClasses:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read NumClasses header!" << endl; return false; } file >> numClasses; file >> word; if( word != "UseScaling:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read UseScaling header!" << endl; return false; } file >> useScaling; file >> word; if( word != "UseNullRejection:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read UseNullRejection header!" << endl; return false; } file >> useNullRejection; if( useScaling ){ file >> word; if( word != "Ranges:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read Ranges header!" << endl; return false; } ranges.resize( numInputDimensions ); for(UINT n=0; n<ranges.size(); n++){ file >> ranges[n].minValue; file >> ranges[n].maxValue; } } file >> word; if( word != "Trained:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read Trained header!" << endl; return false; } file >> trained; file >> word; if( word != "PredictionMethod:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read PredictionMethod header!" << endl; return false; } file >> predictionMethod; if( trained ){ file >> word; if( word != "Models:" ){ errorLog <<"loadModelFromFile(fstream &file) - Failed to read Models header!" << endl; return false; } //Load the models models.resize( numClasses ); classLabels.resize( numClasses ); for(UINT i=0; i<models.size(); i++){ if( !models[i].loadModelFromFile( file ) ){ errorLog << "loadModelFromFile(fstream &file) - Failed to load model " << i << " from file!" << endl; file.close(); return false; } //Set the class label classLabels[i] = models[i].getClassLabel(); } } //Recompute the null rejection thresholds recomputeNullRejectionThresholds(); //Resize the prediction results to make sure it is setup for realtime prediction maxLikelihood = DEFAULT_NULL_LIKELIHOOD_VALUE; bestDistance = DEFAULT_NULL_DISTANCE_VALUE; classLikelihoods.resize(numClasses,DEFAULT_NULL_LIKELIHOOD_VALUE); classDistances.resize(numClasses,DEFAULT_NULL_DISTANCE_VALUE); return true; }
void disk_list<T>::disk(fstream& f, long int k, long int m) { long int i,j,kk; T w, u, t; i=k; j=m; kk=(long)(i+j)/2; f.seekg(kk*sizeof(T)); f.read((char *)&w, sizeof(T)); t = w; do { f.seekg(i*sizeof(T)); f.read((char *)&w, sizeof(T)); while ((strcmp(w.SORT_KEY,t.SORT_KEY)<0)&&(i<=j)) { i=i+1; f.seekg(i*sizeof(T)); f.read((char *)&w, sizeof(T)); } f.seekg(j*sizeof(T)); f.read((char *)&w, sizeof(T)); while ((strcmp(w.SORT_KEY,t.SORT_KEY)>0)&&(i<=j)) { j=j-1; f.seekg(j*sizeof(T)); f.read((char *)&w, sizeof(T)); } if (i<=j) { f.seekg(i*sizeof(T)); f.read((char *)&w, sizeof(T)); f.seekg(j*sizeof(T)); f.read((char *)&u, sizeof(T)); f.seekg(i*sizeof(T)); f.write((char *)&u, sizeof(T)); f.seekg(j*sizeof(T)); f.write((char *)&w, sizeof(T)); i=i+1; j=j-1; } }while (i<=j); if (k<j) disk(f,k,j); if (i<m) disk(f,i,m); return; }
void BLOCK::write(fstream &fp){ fp.write((char*)&bytesUsed, sizeof(bytesUsed)); for(int i = 0; i < bytesUsed; i++) fp.write((char*)&data[i], sizeof(char)); fp.write((char*)&next, sizeof(next)); }
void student::searchdelete(int mode,char key[]) { char pkey[11],buffer[maxlen*2]={0},sname[26],skey[11],number[5]; int offset,r,flag=0; switch(mode) { case 1: case 2: pdx.open(pindex,ios::out|ios::in); while(!pdx.eof()) { pdx>>pkey; pdx>>offset; r=strcmp(pkey,key); if(r==0) { flag = 1; cout<<"\nRecord Found in Primary Index File!\n"; f.open(file,ios::out|ios::in); f.seekg(offset,ios::beg); unpack(); if(mode==1) { f.close(); cout<<"\nName: "<<name; cout<<"\nUSN: "<<usn; cout<<"\nSem: "<<sem; cout<<"\nDept: "<<dept; } else { usn[0] = '*'; f.seekp(offset, ios::beg); pack(1); strcpy(buffer,usn); strcat(buffer,"\t"); sprintf(number,"%d",offset); strcat(buffer,number); pdx.seekp(-(strlen(buffer)),ios::cur); pdx<<buffer<<endl; sdx.open(sindex,ios::out|ios::in); while(!sdx.eof()) { sdx>>sname; sdx>>skey; r=strcmp(skey,pkey); if(r==0) { sname[0] = '*'; strcpy(buffer,sname); strcat(buffer,"\t"); strcat(buffer,usn); sdx.seekp(-(strlen(buffer)),ios::cur); sdx<<buffer<<endl; } } sdx.close(); } break; } } pdx.close(); if(flag==0) cout<<"\nRecord Not found in Primary Index File!\n"; break; case 3: { sdx.open(sindex,ios::out|ios::in ); while (!sdx.eof()) { sdx>>sname; sdx>>skey; r=strcmp(key,sname); if(r==0) { flag = 1; cout<<"\nRecord Found in Secondary Index file! "; searchdelete(1,skey); break; } } if(flag == 0) cout<<"\nRecord Not found in the Secondary Index file \n"; break; } }
void Chunk::Write(fstream &OutputFile) { OutputFile.write(ChunkID, sizeof(ChunkID)); OutputFile.write((const char *)&ChunkSize, sizeof(ChunkSize)); }
/** * \brief Generates the message list * * This function will parse the input file and line by line * and generates a list of message,signal,value table,comments,etc */ void CDBFConverter::GenerateMessageList(fstream& fileInput) { char acLine[defCON_MAX_LINE_LEN]; // I don't expect one line to be more than this string local_copy; char* pcTok; int flag=0; int _flag_BS_= 0; //possible values 0,1,2// this flag is used to check if parsing is done in between NS_: and BS_: #git issue 174 // parsing the input file while(fileInput.getline(acLine, defCON_MAX_LINE_LEN)) { char* pcToken=0, *pcLine=0; for (;;) { pcLine = acLine; pcLine += strlen(pcLine); // go to last position pcLine --; if (*pcLine == '\r') { fileInput.getline(pcLine, defCON_MAX_LINE_LEN); } else { break; } } // avoid leading <spaces> before tokenising, so passing the // starting point will be correct in each case, when calling // msg.Format, sig.Format etc. local_copy = acLine; pcLine = acLine; while(*pcLine && *pcLine == ' ') { *pcLine++; } pcToken = strtok_s(pcLine, " :", &pcTok); if(pcToken) { //compare token to known types to interpret the line further if(strstr(pcToken, "BS_") != NULL) // git issue #174 { if (_flag_BS_ == 1 ) { _flag_BS_ = 2; // this means just NS_ and BS_ are done. } } if(strstr(pcToken, "NS_") != NULL) { if (_flag_BS_ == 0 ) { _flag_BS_ = 1; // this means just NS_ is hit and BS_ is still due. } } // new line - skip else if(strcmp(pcToken, "\n") == 0) { continue; } // message else if(strcmp(pcToken, "BO_") == 0) { CMessage msg; msg.Format(pcLine + strlen(pcToken)+1); // add the new message to the list if((msg.m_acName != "VECTOR__INDEPENDENT_SIG_MSG") && !(msg.m_uiMsgID == 3221225472) ) { if( CAN == m_eBus ) { if( msg.m_ucLength <= 8 ) { CDBFConverter::valid_msg = true; m_listMessages.push_back(msg); } else { CDBFConverter::valid_msg = false; m_unsupList.push_back(msg); } } else { CDBFConverter::valid_msg = true; m_listMessages.push_back(msg); } } else { CDBFConverter::valid_msg = false; } } // signal else if(strcmp(pcToken, "SG_") == 0) { CSignal sig; sig.Format(pcLine + strlen(pcToken) + 1); //if signal associated with a msg add it to that perticular list //elses add it to msg independent list if(CDBFConverter::valid_msg == true) { //insert signals in sorted order int flag = 0; CMessage& msg = m_listMessages.back(); /* if (msg.m_listSignals.empty()) { msg.m_listSignals.push_front(sig); flag = 1; continue; } int count = 0; list<CSignal>::iterator sig1 = msg.m_listSignals.end(); while(sig1!=msg.m_listSignals.begin()) { --sig1; count++; if(((sig1->m_ucWhichByte * 8) + sig1->m_ucStartBit) > ((sig.m_ucWhichByte * 8) + sig.m_ucStartBit)) { ++sig1; msg.m_listSignals.insert(sig1, sig); flag = 1; break; } } if (flag == 0)*/ { msg.m_listSignals.push_back(sig); } // this signal should belong to the last message msg.m_ucNumOfSignals++; // increment the signal count } else { sig.m_ucWhichByte = 1; sig.m_ucStartBit = 0; m_listSignal.push_back(sig); } } // value descriptor else if(strcmp(pcToken, "VAL_") == 0) { // <msgid><sp><signalName><sp><value1><sp><"desc1"><sp><value2><sp><"desc2"> ...; // get MsgId, find the message from the messagelist. // find the signal from the message, then add the value descritors // to the respective signals pcLine = pcLine + strlen(pcToken) + 1; // to get next token pcToken = strtok_s(pcLine, " ", &pcTok); // msgid unsigned int id = (unsigned int) strtoul(pcToken, NULL, 10); if(id != 3221225472) { list<CMessage>::iterator rMsg; for(rMsg=m_listMessages.begin(); rMsg!=m_listMessages.end(); ++rMsg) { // find matching message from list if(rMsg->m_uiMsgID == id) { pcLine = pcLine + strlen(pcToken) + 1; // to get next token pcToken = strtok_s(pcLine, " ", &pcTok); // Signal name list<CSignal>::iterator rSig; // find matching signal for(rSig=rMsg->m_listSignals.begin(); rSig!=rMsg->m_listSignals.end(); ++rSig) { if(rSig->m_acName == pcToken) { rSig->AddValueDescriptors(pcLine + strlen(pcToken) + 1, fileInput); break; // if we got the signal we wanted } } break; // we got the message we wanted } } } else { pcLine = pcLine + strlen(pcToken) + 1; // to get next token pcToken = strtok_s(pcLine, " ", &pcTok); // Signal name list<CSignal>::iterator rSig; // find matching signal for(rSig=m_listSignal.begin(); rSig!=m_listSignal.end(); ++rSig) { if(rSig->m_acName == pcToken) { rSig->AddValueDescriptors(pcLine + strlen(pcToken) + 1, fileInput); break; // if we got the signal we wanted } } } } // signal value qualifier else if(strcmp(pcToken, "SIG_VALTYPE_") == 0) { // <msgID> <signal name> : 1 -- float // <msgID> <signal name> : 2 -- double // get MsgId, find the message from the messagelist. // find the signal from the message, then update the // signal type appropriately of the respective signal pcToken = strtok_s(NULL, " :;", &pcTok); // msgid unsigned int id = (unsigned int)strtoul(pcToken, NULL, 10); if(id != 3221225472) { list<CMessage>::iterator rMsg; for(rMsg=m_listMessages.begin(); rMsg!=m_listMessages.end(); ++rMsg) { // find matching message from list if(rMsg->m_uiMsgID == id) { pcToken = strtok_s(NULL, " :;", &pcTok); // Signal name list<CSignal>::iterator rSig; // find matching signal for(rSig=rMsg->m_listSignals.begin(); rSig!=rMsg->m_listSignals.end(); ++rSig) { if(rSig->m_acName == pcToken) { if(pcToken = strtok_s(NULL, " :;", &pcTok)) // qualifier (1 or 2) { // update signal type based on qualifier switch(*pcToken) { case '1': rSig->m_ucType = CSignal::SIG_TYPE_FLOAT; break; case '2': rSig->m_ucType = CSignal::SIG_TYPE_DOUBLE; break; default: break; } } break; // we got the signal we wanted } } break; // we got the message we wanted } } } else { pcToken = strtok_s(NULL, " :;", &pcTok); // Signal name // find matching signal list<CSignal>::iterator rSig; for(rSig=m_listSignal.begin(); rSig!=m_listSignal.end(); ++rSig) { if(rSig->m_acName == pcToken) { if(pcToken = strtok_s(NULL, " :;", &pcTok)) // qualifier (1 or 2) { // update signal type based on qualifier switch(*pcToken) { case '1': rSig->m_ucType = CSignal::SIG_TYPE_FLOAT; break; case '2': rSig->m_ucType = CSignal::SIG_TYPE_DOUBLE; break; default: break; } } break; // we got the signal we wanted } } } } //value table else if(strcmp(pcToken, "VAL_TABLE_") == 0) { CValueTable tab; pcToken = strtok_s(pcLine, " ", &pcTok); tab.Format(pcLine + strlen(pcToken) + 1, fileInput); m_vTab.push_back(tab); } //comments else if(strcmp(pcToken, "CM_") == 0) { string comment = pcTok; // for network node - venkat pcLine = pcLine + strlen(pcToken) + 1; pcToken = strtok_s(pcLine, " ", &pcTok); CComment cm; //comments related to node if(strcmp(pcToken, "BU_") == 0) { pcToken = strtok_s(NULL, " ", &pcTok); cm.m_elementName= pcToken; pcToken = strtok_s(NULL, "", &pcTok); comment = pcToken; while(strstr(pcToken, "\";") == NULL) { fileInput.getline(acLine, defCON_MAX_LINE_LEN); pcToken = acLine; comment = comment + pcToken; } cm.m_comment= comment; m_cmNode.push_back(cm); } //comments related to messages else if(strcmp(pcToken,"BO_") == 0) { pcToken = strtok_s(NULL, " ", &pcTok); cm.m_msgID = strtoul(pcToken, NULL, 10); // set the id and frame format // canoe puts MSbit = 1 for extended ID if(cm.m_msgID < 0x80000000UL) { cm.m_msgType= 'S'; } else { cm.m_msgType= 'X'; cm.m_msgID &= 0x7FFFFFFF; } pcToken = strtok_s(NULL, "", &pcTok); comment = pcToken; while(strstr(pcToken, "\";") == NULL) { fileInput.getline(acLine, defCON_MAX_LINE_LEN); pcToken = acLine; comment = comment + pcToken; } cm.m_comment= comment; m_cmMsg.push_back(cm); } //comments related to signals else if(strcmp(pcToken, "SG_") == 0) { pcToken = strtok_s(NULL, " ", &pcTok); cm.m_msgID = strtoul(pcToken, NULL, 10); if(cm.m_msgID < 0x80000000UL) { cm.m_msgType = 'S'; } else { cm.m_msgType = 'X'; cm.m_msgID &= 0x7FFFFFFF; } pcToken = strtok_s(NULL, " ", &pcTok); cm.m_elementName = pcToken; pcToken = strtok_s(NULL, "", &pcTok); comment = pcToken; while(strstr(pcToken, "\";") == NULL) { fileInput.getline(acLine, defCON_MAX_LINE_LEN); pcToken = acLine; comment = comment + pcToken; } cm.m_comment= comment; m_cmSig.push_back(cm); } //comments related to network else { //comment = pcToken; int nRetVal = comment.find(";"); if( nRetVal < 0) { while(strstr(pcToken, "\";") == NULL) { fileInput.getline(acLine, defCON_MAX_LINE_LEN); pcToken = acLine; comment = comment + pcToken; } } cm.m_comment= comment; m_cmNet.push_back(cm); } } // node else if(strcmp(pcToken, "BU_") == 0) { create_Node_List(pcLine + strlen(pcToken)+1); } else if ( ( (strcmp(pcToken, "BA_DEF_")==0) || (strcmp(pcToken, "BA_DEF_REL_")==0)) && _flag_BS_ > 1) { CParameter pObj; pObj.Format(pcLine + strlen(pcToken) + 1); // to get next token m_listParameters.push_back(pObj); } //Param Initial Values else if(strcmp(pcToken, "BA_DEF_DEF_")==0 && _flag_BS_ > 1 ) { char acTemp[defCON_TEMP_LEN],*pcTemp; pcTemp = acTemp; pcToken = strtok_s(NULL, "\"", &pcTok); pcToken = strtok_s(NULL, "\"", &pcTok); flag=0; while(*pcToken && *pcToken != '"') { *pcTemp++ = *pcToken++; } *pcTemp = '\0'; list<CParameter>::iterator rParam; for(rParam=m_listParameters.begin(); rParam!=m_listParameters.end(); ++rParam) { // find matching Parameter from list if(rParam->m_ParamName == acTemp) { pcTemp=acTemp; pcToken = strtok_s(NULL, ";", &pcTok); // default val rParam->ReadDefaultVal(pcToken); flag=1; break; } } if(flag==0) { string errString = "BA_DEF_DEF_ \""; errString += acTemp; errString += "\" "; errString += pcToken; errString += _(" : Match not Found in Param List\n"); defList.push_back(errString); } } //RX,Tx Parameter Definition else if(strcmp(pcToken,"BA_DEF_DEF_REL_")==0 && _flag_BS_ > 1) { char acTemp[defCON_TEMP_LEN],*pcTemp; pcTemp = acTemp; flag = 0; pcToken = strtok_s(NULL, "\"", &pcTok); while(*pcToken && (*pcToken != '"')) { *pcTemp++ = *pcToken++; // copy SIG_NAME only, i.e. till first 'space' } *pcTemp = '\0'; list<CParameter>::iterator rParam; for(rParam=m_listParameters.begin(); rParam!=m_listParameters.end(); ++rParam) { // find matching Parameter from list if(rParam->m_ParamName == acTemp) { pcTemp = acTemp; pcToken = strtok_s(NULL, ";", &pcTok); // default val rParam->ReadDefaultVal(pcToken); flag=1; break; } } if(flag==0) { string errString = "BA_DEF_DEF_REL \""; errString += acTemp; errString += "\" "; errString += pcToken; errString += _(" : Match not Found in Param List\n"); defList.push_back(errString); } } // Parameter Other values // else if(strcmp(pcToken, "BA_")==0) { char acTemp[defCON_TEMP_LEN],*pcTemp; pcTemp = acTemp; while(*pcLine && (*pcLine == ' ')) { *pcLine++; } //get Param name pcLine = pcLine + strlen(pcToken) + 1; pcToken = strtok_s(pcLine, "\"", &pcTok); while(*pcToken && (*pcToken != '"')) { *pcTemp++ = *pcToken++; } *pcTemp = '\0'; list<CParameter>::iterator rParam; for(rParam=m_listParameters.begin(); rParam!=m_listParameters.end(); ++rParam) { // find matching Parameter from list if(rParam->m_ParamName == acTemp) { rParam->FormatParamValue(pcLine + strlen(acTemp) + 3); // to get next token pcTemp=acTemp; if(rParam->m_ParamName == SIGNAL_LONG_NAME) { CParameterValues uParamVal = rParam->m_listParamValues[3].back(); vUpdateSignalNameFromParam(uParamVal); int i = 0; } else if(rParam->m_ParamName == MESSAGE_LONG_NAME) { CParameterValues uParamVal = rParam->m_listParamValues[2].back(); vUpdateMessageNameFromParam(uParamVal); int i = 0; } break; } } } //maintain a list of lines not processed else { string str = local_copy; m_notProcessed.push_back(str); continue; } } } }
void Decryptor::output(char* outFileName) { outFile.open(outFileName,fstream::out | ios::binary); outFile << cylines; outFile.close(); }
void inits() { errno = 0; logfile.open(LOGFILEPATH, std::fstream::out | std::fstream::app); logger << "RasPiProg logging started." << endl; sa.sa_handler = &sighandler; sa.sa_flags = SA_RESTART; sigfillset(&sa.sa_mask); if(sigaction(SIGTERM, &sa, NULL) == -1) { logger << "Error: cannot handle SIGTERM" << endl; } if(sigaction(SIGHUP, &sa, NULL) == -1) { logger << "Error: cannot handle SIGHUP" << endl; } if(sigaction(SIGUSR1, &sa, NULL) == -1) { logger << "Error: cannot handle SIGUSR1" << endl; } if(sigaction(SIGINT, &sa, NULL) == -1) { logger << "Error: cannot handle SIGINT" << endl; } if(wiringPiSetup() == -1) { logger << "WiringPi initialization failed!" << endl; exit(1); } lcdHandle = lcdInit(lcdSettings[0],lcdSettings[1],lcdSettings[2],lcdSettings[3],lcdSettings[4],lcdSettings[5],lcdSettings[6] ,lcdSettings[7],lcdSettings[8],lcdSettings[9],lcdSettings[10],lcdSettings[11],lcdSettings[12]); if(lcdHandle < 0) { logger << "LCD-display initialization failed!" << endl; exit(2); } lcdClear(lcdHandle); lcdPosition(lcdHandle, 0, 0) ; lcdPuts(lcdHandle, "RasPiProg By PTapioK"); sleep(1); lcdClear(lcdHandle); /* int lirc = lirc_init(sqlDBname, 1); if(lirc == -1) { logger << "Lirc initialization failed!" << endl; exit(3); } if(lirc_readconfig(NULL, &config, NULL) == -1) { logger << "Lirc initialization failed!" << endl; exit(4); } // Don't wait IR signals fcntl(lirc, F_SETOWN, getpid()); int flags = fcntl(lirc, F_GETFL, 0); if (flags == -1) deinits(); fcntl(lirc, F_SETFL, flags | O_NONBLOCK); */ sqlCon = mysql_init(NULL); if(sqlCon == NULL) { logger << "MySQL initialization failed!" << endl; exit(5); } if(mysql_real_connect(sqlCon, sqlHost.c_str(), sqlUsername.c_str(), sqlPassword.c_str(), sqlDBname.c_str(), 0, NULL, 0) == NULL) { // Try again if(mysql_real_connect(sqlCon, sqlHost.c_str(), sqlUsername.c_str(), sqlPassword.c_str(), sqlDBname.c_str(), 0, NULL, 0) == NULL) { logger << "MySQL connection initialization failed!" << endl; mysql_close(sqlCon); exit(6); } } if(!TableExists(sqlDBname, "temps")) { if(mysql_query(sqlCon, "CREATE TABLE temps(id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, name TEXT, st TIMESTAMP DEFAULT CURRENT_TIMESTAMP, temp FLOAT)")) { logger << "MySQL error! Errno: " << mysql_errno(sqlCon) << endl; mysql_close(sqlCon); exit(8); } } if(!TableExists(sqlDBname, "humis")) { if(mysql_query(sqlCon, "CREATE TABLE humis(id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, name TEXT, st TIMESTAMP DEFAULT CURRENT_TIMESTAMP, humi FLOAT)")) { logger << "MySQL error! Errno: " << mysql_errno(sqlCon) << endl; mysql_close(sqlCon); exit(8); } } if(!TableExists(sqlDBname, "presss")) { if(mysql_query(sqlCon, "CREATE TABLE presss(id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, name TEXT, st TIMESTAMP DEFAULT CURRENT_TIMESTAMP, press FLOAT)")) { logger << "MySQL error! Errno: " << mysql_errno(sqlCon) << endl; mysql_close(sqlCon); exit(8); } } if(!TableExists(sqlDBname, "latestrecords")) { if(mysql_query(sqlCon, "CREATE TABLE latestrecords(name VARCHAR(30), type VARCHAR(6), st TIMESTAMP DEFAULT CURRENT_TIMESTAMP, data FLOAT, PRIMARY KEY (name, type))")) { logger << "MySQL error! Errno: " << mysql_errno(sqlCon) << endl; mysql_close(sqlCon); exit(8); } } if(mysql_query(sqlCon, "SET CHARACTER SET utf8")) { logger << "MySQL error! Errno: " << mysql_errno(sqlCon) << endl; mysql_close(sqlCon); exit(10); } /* if(mcp3004Setup(BASE, SPI_CHAN) == -1) { logger << "MCP3008 chip initialization failed!" << endl; exit(7); } */ if ((i2cfile = open(I2CBus, O_RDWR)) < 0) { logger << endl; logger << "Failed to open the i2c bus! Errno: " << errno << endl; logger << endl; exit(11); } // Pin 20 is DHT22 power pin. pinMode(20, OUTPUT); digitalWrite(20, HIGH); sleep(5); }
void myfile::fileclose () { fp.close (); }
bool ANBC::loadModelFromFile(fstream &file) { trained = false; numFeatures = 0; numClasses = 0; models.clear(); classLabels.clear(); if(!file.is_open()) { errorLog << "loadANBCModelFromFile(string filename) - Could not open file to load model" << endl; return false; } std::string word; //Find the file type header file >> word; if(word != "GRT_ANBC_MODEL_FILE_V1.0") { errorLog << "loadANBCModelFromFile(string filename) - Could not find Model File Header" << endl; return false; } file >> word; if(word != "NumFeatures:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find NumFeatures " << endl; return false; } file >> numFeatures; file >> word; if(word != "NumClasses:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find NumClasses" << endl; return false; } file >> numClasses; file >> word; if(word != "UseScaling:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find UseScaling" << endl; return false; } file >> useScaling; file >> word; if(word != "UseNullRejection:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find UseNullRejection" << endl; return false; } file >> useNullRejection; ///Read the ranges if needed if( useScaling ) { //Resize the ranges buffer ranges.resize(numFeatures); file >> word; if(word != "Ranges:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find the Ranges" << endl; return false; } for(UINT n=0; n<ranges.size(); n++) { file >> ranges[n].minValue; file >> ranges[n].maxValue; } } //Resize the buffer models.resize(numClasses); classLabels.resize(numClasses); //Load each of the K models for(UINT k=0; k<numClasses; k++) { UINT modelID; file >> word; if(word != "*************_MODEL_*************") { errorLog << "loadANBCModelFromFile(string filename) - Could not find header for the "<<k+1<<"th model" << endl; return false; } file >> word; if(word != "Model_ID:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find model ID for the "<<k+1<<"th model" << endl; return false; } file >> modelID; if(modelID-1!=k) { cout<<"ANBC: Model ID does not match the current class ID for the "<<k+1<<"th model" << endl; return false; } file >> word; if(word != "N:") { cout<<"ANBC: Could not find N for the "<<k+1<<"th model" << endl; return false; } file >> models[k].N; file >> word; if(word != "ClassLabel:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find ClassLabel for the "<<k+1<<"th model" << endl; return false; } file >> models[k].classLabel; classLabels[k] = models[k].classLabel; file >> word; if(word != "Threshold:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find the threshold for the "<<k+1<<"th model" << endl; return false; } file >> models[k].threshold; file >> word; if(word != "Gamma:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find the gamma parameter for the "<<k+1<<"th model" << endl; return false; } file >> models[k].gamma; file >> word; if(word != "TrainingMu:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find the training mu parameter for the "<<k+1<<"th model" << endl; return false; } file >> models[k].trainingMu; file >> word; if(word != "TrainingSigma:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find the training sigma parameter for the "<<k+1<<"th model" << endl; return false; } file >> models[k].trainingSigma; //Resize the buffers models[k].mu.resize(numFeatures); models[k].sigma.resize(numFeatures); models[k].weights.resize(numFeatures); //Load Mu, Sigma and Weights file >> word; if(word != "Mu:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find the Mu vector for the "<<k+1<<"th model" << endl; return false; } //Load Mu for(UINT j=0; j<models[k].N; j++) { double value; file >> value; models[k].mu[j] = value; } file >> word; if(word != "Sigma:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find the Sigma vector for the "<<k+1<<"th model" << endl; return false; } //Load Sigma for(UINT j=0; j<models[k].N; j++) { double value; file >> value; models[k].sigma[j] = value; } file >> word; if(word != "Weights:") { errorLog << "loadANBCModelFromFile(string filename) - Could not find the Weights vector for the "<<k+1<<"th model" << endl; return false; } //Load Weights for(UINT j=0; j<models[k].N; j++) { double value; file >> value; models[k].weights[j] = value; } file >> word; if(word != "*********************************") { errorLog << "loadANBCModelFromFile(string filename) - Could not find the model footer for the "<<k+1<<"th model" << endl; return false; } } //Flag that the model is trained trained = true; //Recompute the null rejection thresholds recomputeNullRejectionThresholds(); //Resize the prediction results to make sure it is setup for realtime prediction maxLikelihood = DEFAULT_NULL_LIKELIHOOD_VALUE; bestDistance = DEFAULT_NULL_DISTANCE_VALUE; classLikelihoods.resize(numClasses,DEFAULT_NULL_LIKELIHOOD_VALUE); classDistances.resize(numClasses,DEFAULT_NULL_DISTANCE_VALUE); return true; }
bool LDA::loadModelFromFile(fstream &file){ trained = false; numInputDimensions = 0; numClasses = 0; models.clear(); classLabels.clear(); if(!file.is_open()) { errorLog << "loadModelFromFile(fstream &file) - The file is not open!" << endl; return false; } std::string word; //Find the file type header file >> word; if(word != "GRT_LDA_MODEL_FILE_V1.0"){ errorLog << "loadModelFromFile(fstream &file) - Could not find Model File Header" << endl; return false; } file >> word; if(word != "NumFeatures:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find NumFeatures " << endl; return false; } file >> numInputDimensions; file >> word; if(word != "NumClasses:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find NumClasses" << endl; return false; } file >> numClasses; file >> word; if(word != "UseScaling:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find UseScaling" << endl; return false; } file >> useScaling; file >> word; if(word != "UseNullRejection:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find UseNullRejection" << endl; return false; } file >> useNullRejection; ///Read the ranges if needed if( useScaling ){ //Resize the ranges buffer ranges.resize(numInputDimensions); file >> word; if(word != "Ranges:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find the Ranges" << endl; return false; } for(UINT n=0; n<ranges.size(); n++){ file >> ranges[n].minValue; file >> ranges[n].maxValue; } } //Resize the buffer models.resize(numClasses); classLabels.resize(numClasses); //Load each of the K models for(UINT k=0; k<numClasses; k++){ file >> word; if(word != "ClassLabel:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find ClassLabel for the "<<k+1<<"th model" << endl; return false; } file >> models[k].classLabel; classLabels[k] = models[k].classLabel; file >> word; if(word != "PriorProbability:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find the PriorProbability for the "<<k+1<<"th model" << endl; return false; } file >> models[k].priorProb; models[k].weights.resize(numInputDimensions+1); //Load the weights file >> word; if(word != "Weights:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find the Weights vector for the "<<k+1<<"th model" << endl; return false; } //Load Weights for(UINT j=0; j<numInputDimensions+1; j++){ double value; file >> value; models[k].weights[j] = value; } } //Resize the prediction results to make sure it is setup for realtime prediction maxLikelihood = DEFAULT_NULL_LIKELIHOOD_VALUE; bestDistance = DEFAULT_NULL_DISTANCE_VALUE; classLikelihoods.resize(numClasses,DEFAULT_NULL_LIKELIHOOD_VALUE); classDistances.resize(numClasses,DEFAULT_NULL_DISTANCE_VALUE); trained = true; return true; }
/* 在磁盘上创建日志文件 如果已经有了,就在文件后接着写,反正每天一个 */ void logger::createLogFile(fstream &file, string filePath) { file.open(filePath.c_str(), ios_base::out | ios_base::app); }
void afisare() { g<<rez<<endl; g.close(); }
bool GMM::loadModelFromFile(fstream &file){ trained = false; numInputDimensions = 0; numClasses = 0; models.clear(); classLabels.clear(); if(!file.is_open()) { errorLog << "loadModelFromFile(fstream &file) - Could not open file to load model" << endl; return false; } std::string word; file >> word; //Check to see if we should load a legacy file if( word == "GRT_GMM_MODEL_FILE_V1.0" ){ return loadLegacyModelFromFile( file ); } //Find the file type header if(word != "GRT_GMM_MODEL_FILE_V2.0"){ errorLog << "loadModelFromFile(fstream &file) - Could not find Model File Header" << endl; return false; } //Load the base settings from the file if( !Classifier::loadBaseSettingsFromFile(file) ){ errorLog << "loadModelFromFile(string filename) - Failed to load base settings from file!" << endl; return false; } file >> word; if(word != "NumMixtureModels:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find NumMixtureModels" << endl; return false; } file >> numMixtureModels; if( trained ){ //Read the model header file >> word; if(word != "Models:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find the Models Header" << endl; return false; } //Resize the buffer models.resize(numClasses); classLabels.resize(numClasses); //Load each of the models for(UINT k=0; k<numClasses; k++){ UINT classLabel = 0; UINT K = 0; double normalizationFactor; double trainingMu; double trainingSigma; double rejectionThreshold; file >> word; if(word != "ClassLabel:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find the ClassLabel for model " << k+1 << endl; return false; } file >> classLabel; models[k].setClassLabel( classLabel ); classLabels[k] = classLabel; file >> word; if(word != "K:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find K for model " << k+1 << endl; return false; } file >> K; file >> word; if(word != "NormalizationFactor:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find NormalizationFactor for model " << k+1 << endl; return false; } file >> normalizationFactor; models[k].setNormalizationFactor(normalizationFactor); file >> word; if(word != "TrainingMu:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find TrainingMu for model " << k+1 << endl; return false; } file >> trainingMu; file >> word; if(word != "TrainingSigma:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find TrainingSigma for model " << k+1 << endl; return false; } file >> trainingSigma; //Set the training mu and sigma models[k].setTrainingMuAndSigma(trainingMu, trainingSigma); file >> word; if(word != "NullRejectionThreshold:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find NullRejectionThreshold for model " << k+1 << endl; return false; } file >>rejectionThreshold; //Set the rejection threshold models[k].setNullRejectionThreshold(rejectionThreshold); //Resize the buffer for the mixture models models[k].resize(K); //Load the mixture models for(UINT index=0; index<models[k].getK(); index++){ //Resize the memory for the current mixture model models[k][index].mu.resize( numInputDimensions ); models[k][index].sigma.resize( numInputDimensions, numInputDimensions ); models[k][index].invSigma.resize( numInputDimensions, numInputDimensions ); file >> word; if(word != "Determinant:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find the Determinant for model " << k+1 << endl; return false; } file >> models[k][index].det; file >> word; if(word != "Mu:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find Mu for model " << k+1 << endl; return false; } for(UINT j=0; j<models[k][index].mu.size(); j++){ file >> models[k][index].mu[j]; } file >> word; if(word != "Sigma:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find Sigma for model " << k+1 << endl; return false; } for(UINT i=0; i<models[k][index].sigma.getNumRows(); i++){ for(UINT j=0; j<models[k][index].sigma.getNumCols(); j++){ file >> models[k][index].sigma[i][j]; } } file >> word; if(word != "InvSigma:"){ errorLog << "loadModelFromFile(fstream &file) - Could not find InvSigma for model " << k+1 << endl; return false; } for(UINT i=0; i<models[k][index].invSigma.getNumRows(); i++){ for(UINT j=0; j<models[k][index].invSigma.getNumCols(); j++){ file >> models[k][index].invSigma[i][j]; } } } } //Set the null rejection thresholds nullRejectionThresholds.resize(numClasses); for(UINT k=0; k<numClasses; k++) { models[k].recomputeNullRejectionThreshold(nullRejectionCoeff); nullRejectionThresholds[k] = models[k].getNullRejectionThreshold(); } maxLikelihood = DEFAULT_NULL_LIKELIHOOD_VALUE; bestDistance = DEFAULT_NULL_DISTANCE_VALUE; classLikelihoods.resize(numClasses,DEFAULT_NULL_LIKELIHOOD_VALUE); classDistances.resize(numClasses,DEFAULT_NULL_DISTANCE_VALUE); } return true; }