int main() { int n; in >> n; graph.resize(n); colors.resize(n, 0); vector <pair <int, int> > badGraph; int curr; for (int i = 0; i != n; ++i) { in >> curr; if (i == 0) continue; if (i == 0 || curr == -1) continue; if (i + curr > n) fail(); for (int j = 0; j != curr; ++j) { graph[i + j].push_back(j); graph[j].push_back(i + j); } if (i + curr != n) { badGraph.push_back(make_pair(i + curr, curr)); badGraph.push_back(make_pair(curr, i + curr)); } } int amountColors = 0; for (int i = 0; i != n; ++i) if (!colors[i]) paint(i, ++amountColors); newGraph.resize(amountColors + 2); newColors.resize(amountColors + 2); for (vector <pair <int, int> >::const_iterator it = badGraph.begin(); it != badGraph.end(); ++it) { //if (colors[it->first] == colors[it->second]) // fail(); newGraph[colors[it->first]].push_back(colors[it->second]); } unsigned long long answer = 1, mod = 1000000007; for (int i = 1; i <= amountColors; ++i) { if (!newColors[i]) { check(i); answer = (2 * answer) % mod; } } out << answer; in.close(); out.close(); return 0; }
bool pgmb_read_data ( ifstream &input, int xsize, int ysize, unsigned char *g ) //****************************************************************************80 // // Purpose: // // PGMB_READ_DATA reads the data in a binary portable gray map file. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 16 December 2004 // // Author: // // John Burkardt // // Parameters: // // Input, ifstream &INPUT, a pointer to the file containing the binary // portable gray map data. // // Input, int XSIZE, YSIZE, the number of rows and columns of data. // // Output, unsigned char *G, the array of XSIZE by YSIZE data values. // // Output, bool PGMB_READ_DATA, is true if an error occurred. // { char c; bool error; int i; unsigned char *indexg; int j; indexg = g; for ( j = 0; j < ysize; j++ ) { for ( i = 0; i < xsize; i++ ) { input.read ( &c, 1 ); *indexg = ( unsigned char ) c; indexg = indexg + 1; error = input.eof(); if ( error ) { cout << "\n"; cout << "PGMB_READ_DATA - Fatal error!\n"; cout << " End of file reading pixel (" << i << ", " << j <<") \n"; return true; } } } return false; }
bool pgmb_read_header ( ifstream &input, int *xsize, int *ysize, unsigned char *maxg ) //****************************************************************************80 // // Purpose: // // PGMB_READ_HEADER reads the header of a binary portable gray map file. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 16 April 2003 // // Author: // // John Burkardt // // Parameters: // // Input, ifstream &INPUT, a pointer to the file containing the binary // portable gray map data. // // Output, int *XSIZE, *YSIZE, the number of rows and columns of data. // // Output, unsigned char *MAXG, the maximum gray value. // // Output, bool PGMB_READ_HEADER, is true if an error occurred. // { int count; int fred; string line; int maxg2; string rest; int step; int width; string word; step = 0; while ( 1 ) { getline ( input, line ); if ( input.eof ( ) ) { cout << "\n"; cout << "PGMB_READ_HEADER - Fatal error!\n"; cout << " End of file.\n"; return true; } if ( line[0] == '#' ) { continue; } if ( step == 0 ) { s_word_extract_first ( line, word, rest ); if ( s_len_trim ( word ) <= 0 ) { continue; } if ( !s_eqi ( word, "P5" ) ) { cout << "\n"; cout << "PGMB_READ_HEADER - Fatal error.\n"; cout << " Bad magic number = \"" << word << "\".\n"; return true; } line = rest; step = 1; } if ( step == 1 ) { s_word_extract_first ( line, word, rest ); if ( s_len_trim ( word ) <= 0 ) { continue; } *xsize = atoi ( word.c_str ( ) ); line = rest; step = 2; } if ( step == 2 ) { s_word_extract_first ( line, word, rest ); if ( s_len_trim ( word ) <= 0 ) { continue; } *ysize = atoi ( word.c_str ( ) ); line = rest; step = 3; } if ( step == 3 ) { s_word_extract_first ( line, word, rest ); if ( s_len_trim ( word ) <= 0 ) { continue; } fred = atoi ( word.c_str ( ) ); *maxg = ( unsigned char ) fred; line = rest; break; } } return false; }
//******************************************************************************************************************** //******************************************************************************************************************** void closefiles(ifstream& files, ofstream& outfile, ofstream& errorfile) { files.close(); outfile.close(); errorfile.close(); }
static string read_line(ifstream &file){ static char buffer[BUFFER_SIZE]; file.get(buffer,BUFFER_SIZE); file.get(); return string(buffer); }
/************************************************************************************************* map<string, int> Bayesian::parseTaxMap(string newTax) { try{ map<string, int> parsed; newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';' //parse taxonomy string individual; while (newTax.find_first_of(';') != -1) { individual = newTax.substr(0,newTax.find_first_of(';')); newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length()); parsed[individual] = 1; } //get last one parsed[newTax] = 1; return parsed; } catch(exception& e) { m->errorOut(e, "Bayesian", "parseTax"); exit(1); } } **************************************************************************************************/ void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) { try { //read version string line = m->getline(in); m->gobble(in); in >> numKmers; m->gobble(in); //initialze probabilities wordGenusProb.resize(numKmers); for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); } int kmer, name, count; count = 0; vector<int> num; num.resize(numKmers); float prob; vector<float> zeroCountProb; zeroCountProb.resize(numKmers); for (int j = 0; j < numKmers; j++) { diffPair tempDiffPair; WordPairDiffArr.push_back(tempDiffPair); } //read version string line2 = m->getline(inNum); m->gobble(inNum); float probTemp; while (inNum) { inNum >> zeroCountProb[count] >> num[count] >> probTemp; WordPairDiffArr[count].prob = probTemp; count++; m->gobble(inNum); } inNum.close(); while(in) { in >> kmer; //set them all to zero value for (int i = 0; i < genusNodes.size(); i++) { wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1)); } //get probs for nonzero values for (int i = 0; i < num[kmer]; i++) { in >> name >> prob; wordGenusProb[kmer][name] = prob; } m->gobble(in); } in.close(); } catch(exception& e) { m->errorOut(e, "Bayesian", "readProbFile"); exit(1); } }
bool Bayesian::checkReleaseDate(ifstream& file1, ifstream& file2, ifstream& file3, ifstream& file4) { try { bool good = true; vector<string> lines; lines.push_back(m->getline(file1)); lines.push_back(m->getline(file2)); lines.push_back(m->getline(file3)); lines.push_back(m->getline(file4)); //before we added this check if ((lines[0][0] != '#') || (lines[1][0] != '#') || (lines[2][0] != '#') || (lines[3][0] != '#')) { good = false; } else { //rip off # for (int i = 0; i < lines.size(); i++) { lines[i] = lines[i].substr(1); } //get mothurs current version string version = m->getVersion(); vector<string> versionVector; m->splitAtChar(version, versionVector, '.'); //check each files version for (int i = 0; i < lines.size(); i++) { vector<string> linesVector; m->splitAtChar(lines[i], linesVector, '.'); if (versionVector.size() != linesVector.size()) { good = false; break; } else { for (int j = 0; j < versionVector.size(); j++) { int num1, num2; convert(versionVector[j], num1); convert(linesVector[j], num2); //if mothurs version is newer than this files version, then we want to remake it if (num1 > num2) { good = false; break; } } } if (!good) { break; } } } if (!good) { file1.close(); file2.close(); file3.close(); file4.close(); } else { file1.seekg(0); file2.seekg(0); file3.seekg(0); file4.seekg(0); } return good; } catch(exception& e) { m->errorOut(e, "Bayesian", "checkReleaseDate"); exit(1); } }
void GlowNodeClass::open( ifstream& fp) { int type; int end_found = 0; char dummy[40]; int tmp; int i, j; char c; int sts; for (;;) { if ( !fp.good()) { fp.clear(); fp.getline( dummy, sizeof(dummy)); printf( "** Read error GlowNodeClass: \"%d %s\"\n", type, dummy); } fp >> type; switch( type) { case glow_eSave_NodeClass: break; case glow_eSave_NodeClass_nc_name: fp.get(); fp.getline( nc_name, sizeof(nc_name)); break; case glow_eSave_NodeClass_a: a.open( ctx, fp); break; case glow_eSave_NodeClass_group: fp >> tmp; group = (glow_eNodeGroup)tmp; break; case glow_eSave_NodeClass_dynamicsize: fp >> dynamicsize; break; case glow_eSave_NodeClass_dynamic: fp.getline( dummy, sizeof(dummy)); if ( dynamicsize) { dynamic = (char *) calloc( 1, dynamicsize); fp.get(); for ( j = 0; j < dynamicsize; j++) { if ((c = fp.get()) == '"') { if ( dynamic[j-1] == '\\') j--; else { dynamic[j] = 0; break; } } dynamic[j] = c; } fp.getline( dummy, sizeof(dummy)); } break; case glow_eSave_NodeClass_arg_cnt: fp >> arg_cnt; break; case glow_eSave_NodeClass_argname: fp.get(); for ( i = 0; i < arg_cnt; i++) { fp.getline( argname[i], sizeof(argname[0])); } break; case glow_eSave_NodeClass_argtype: for ( i = 0; i < arg_cnt; i++) fp >> argtype[i]; break; case glow_eSave_NodeClass_dyn_type1: fp >> dyn_type1; break; case glow_eSave_NodeClass_dyn_type2: fp >> dyn_type2; break; case glow_eSave_NodeClass_dyn_action_type1: fp >> dyn_action_type1; break; case glow_eSave_NodeClass_dyn_action_type2: fp >> dyn_action_type2; break; case glow_eSave_NodeClass_dyn_color1: fp >> tmp; dyn_color[0] = (glow_eDrawType)tmp; break; case glow_eSave_NodeClass_dyn_color2: fp >> tmp; dyn_color[1] = (glow_eDrawType)tmp; break; case glow_eSave_NodeClass_dyn_color3: fp >> tmp; dyn_color[2] = (glow_eDrawType)tmp; break; case glow_eSave_NodeClass_dyn_color4: fp >> tmp; dyn_color[3] = (glow_eDrawType)tmp; break; case glow_eSave_NodeClass_dyn_attr1: fp >> dyn_attr[0]; break; case glow_eSave_NodeClass_dyn_attr2: fp >> dyn_attr[1]; break; case glow_eSave_NodeClass_dyn_attr3: fp >> dyn_attr[2]; break; case glow_eSave_NodeClass_dyn_attr4: fp >> dyn_attr[3]; break; case glow_eSave_NodeClass_no_con_obstacle: fp >> no_con_obstacle; break; case glow_eSave_NodeClass_slider: fp >> slider; break; case glow_eSave_NodeClass_java_name: fp.get(); fp.getline( java_name, sizeof(java_name)); break; case glow_eSave_NodeClass_next_nodeclass: fp.get(); fp.getline( next_nodeclass, sizeof(next_nodeclass)); break; case glow_eSave_NodeClass_animation_count: fp >> animation_count; break; case glow_eSave_NodeClass_cycle: fp >> tmp; cycle = (glow_eCycle)tmp; break; case glow_eSave_NodeClass_y0: fp >> y0; break; case glow_eSave_NodeClass_y1: fp >> y1; break; case glow_eSave_NodeClass_x0: fp >> x0; break; case glow_eSave_NodeClass_x1: fp >> x1; break; case glow_eSave_NodeClass_input_focus_mark: fp >> tmp; input_focus_mark = (glow_eInputFocusMark)tmp; break; case glow_eSave_NodeClass_recursive_trace: fp >> recursive_trace; break; case glow_eSave_NodeClass_userdata_cb: if ( ctx->userdata_open_callback) (ctx->userdata_open_callback)(&fp, this, glow_eUserdataCbType_NodeClass); break; case glow_eSave_End: end_found = 1; break; default: cout << "GlowNodeClass:open syntax error" << endl; fp.getline( dummy, sizeof(dummy)); } if ( end_found) break; } if ( strcmp( next_nodeclass, "") != 0) { next_nc = ctx->get_nodeclass_from_name( next_nodeclass); if ( !next_nc) { sts = ctx->open_subgraph_from_name( next_nodeclass, glow_eSaveMode_SubGraph); if ( ODD(sts)) { next_nc = ctx->get_nodeclass_from_name( next_nodeclass); if ( next_nc) ((GlowNodeClass *)next_nc)->nc_extern = nc_extern; } } if ( !next_nc) cout << "GlowNode:next_nodeclass not found: " << nc_name << " " << next_nodeclass << endl; else if ( ((GlowNodeClass *)next_nc)->prev_nc) { next_nc = 0; cout << "GlowNode:next_nodeclass already chained: " << nc_name << " " << next_nodeclass << endl; } else ((GlowNodeClass *)next_nc)->prev_nc = (GlowArrayElem *) this; } }
/* ********************************************************************************************* */ void processPrimitivesWFN(ifstream &ifil,const int npr,int* &pricen,int* &primty,solreal* &prexp) { alloc1DIntArray("pricen",npr,pricen); alloc1DIntArray("primty",npr,primty); alloc1DRealArray("prexp",npr,prexp); int count=0; int pos; /* Getting the primitive centers */ pos=ifil.tellg(); ifil.seekg(pos+20); for (int i=0; i<npr; i++) { ifil >> pricen[i]; pricen[i]--; count++; if (count==20) { pos=ifil.tellg(); ifil.seekg(pos+20); count=0; } //cout << pricen[i] << " "; } if ((npr%20)==0) { pos=ifil.tellg(); ifil.seekg(pos-20); } /* Getting the primitive types */ pos=ifil.tellg(); ifil.seekg(pos+20); count=0; for (int i=0; i<npr; i++) { ifil >> primty[i]; primty[i]--; count++; if (count==20) { pos=ifil.tellg(); ifil.seekg(pos+20); count=0; } //cout << primty[i] << " "; } if ((npr%20)==0) { pos=ifil.tellg(); ifil.seekg(pos-20); } /* Getting the primitive exponents */ string line; int nolines; nolines=floor(npr/5); if ((npr%5)>0) {nolines++;} count=0; for (int i=0; i<nolines; i++) { pos=ifil.tellg(); getline(ifil,line); if (line.length()==0) {getline(ifil,line); pos++;} line.erase(0,10); for (int j=0; j<5; j++) { if (count<npr) { if ((line[10]=='D')||(line[10]=='d')) { line[10]='e'; } prexp[count]=(solreal)atof((line.substr(0,14)).c_str()); count++; line.erase(0,14); } } } }
bool Entity_CollisionType_Puzzle_Barrier::unserialize(ifstream& file) { if(!file.is_open()) return false; int Entity_CollisionType_Puzzle_Barrier_version; file.read((char*) &Entity_CollisionType_Puzzle_Barrier_version, sizeof(int)); if(Entity_CollisionType_Puzzle_Barrier_version==1){ file.read((char*) &x, sizeof(x)); file.read((char*) &y, sizeof(y)); file.read((char*) &w, sizeof(w)); file.read((char*) &h, sizeof(h)); bounds.x = x-(w/2); bounds.y = y-(h/2); bounds.w = w; bounds.h = h; return true; } else if(Entity_CollisionType_Puzzle_Barrier_version==2){ file.read((char*) &x, sizeof(x)); file.read((char*) &y, sizeof(y)); file.read((char*) &w, sizeof(w)); file.read((char*) &h, sizeof(h)); file.read((char*) &tied_respawn_zone_index, sizeof(tied_respawn_zone_index)); bounds.x = x-(w/2); bounds.y = y-(h/2); bounds.w = w; bounds.h = h; return true; } else if(Entity_CollisionType_Puzzle_Barrier_version==3){ file.read((char*) &x, sizeof(x)); file.read((char*) &y, sizeof(y)); file.read((char*) &w, sizeof(w)); file.read((char*) &h, sizeof(h)); file.read((char*) &tied_respawn_zone_index, sizeof(tied_respawn_zone_index)); file.read((char*) &index, sizeof(index)); bounds.x = x-(w/2); bounds.y = y-(h/2); bounds.w = w; bounds.h = h; return true; } else return false; }
void CellPositionInitialiser::initFromFileForMicroFluidic(Agent *ag, ifstream& input, ifstream& geo) { cerr << "# starting all cells at a position based on a microfluidic file (initFromFileForMicroFluidic) " << endl; //go to the beginning of the file input.seekg(0,ios::beg); geo.seekg(0,ios::beg); // some local variables. string line = ""; istringstream iss; string line2 = ""; istringstream iss2; string from = ","; string to = " "; size_t lookHere; size_t foundHere; int voxel_index = 0; int num_cells = 0; int value = 0; vector<double> coordinate(3); // get the database of the agent Database *db = ag->getDatabase(); // get cell_positions TVectorData<TVectorData<double>* > *cell_positions = (TVectorData<TVectorData<double>* >*) db->getDataItem("cellpositions"); // get environment grid Grid *g = (Grid *) db->getDataItem("environment"); // get cell_voxel_positions TVectorData<int> *cell_voxel_positions = (TVectorData<int>* ) db->getDataItem("cell_voxel_positions"); // get number cells_per_voxel TVectorData<int> *number_cells_per_voxel = (TVectorData<int>* ) db->getDataItem("number_cells_per_voxel"); number_cells_per_voxel->reserveSize(g->getNumberOfVoxels()); for (int i=0; i<g->getNumberOfVoxels(); i++) number_cells_per_voxel->at(i) = 0; // iterate over the input while (getline(input,line)) { lookHere = 0; // remove comma delimiters and change them to empty spaces while ((foundHere = line.find(from, lookHere)) != string::npos) { line.replace(foundHere,from.size(),to); lookHere = foundHere + to.size(); } // remove comma delimiters from geometry file getline(geo,line2); lookHere = 0; while ((foundHere = line2.find(from, lookHere)) != string::npos) { line2.replace(foundHere,from.size(),to); lookHere = foundHere + to.size(); } iss.clear(); // cell input iss.str(line); iss2.clear(); // geometry input iss2.str(line2); while (iss2 >> value) { iss >> num_cells; // if we have a real voxel if (value == 1) { // get the center coordinate of the voxel that we currently are dealing with g->getCenterOfVoxel(voxel_index++, coordinate); // add cells to the system for (int i=0; i<num_cells; i++) { // add a position to the cell positions vector TVectorData<double> *pos = new TVectorData<double>("position", "tvectordata_double"); pos->reserveSize(3); pos->at(0) = coordinate[0]; pos->at(1) = coordinate[1]; pos->at(2) = coordinate[2]; cell_positions->addElementToEnd(pos); // add an entry to the cell_voxel_positions vector cell_voxel_positions->addElementToEnd(voxel_index-1); // update number cells per voxel number_cells_per_voxel->at(voxel_index-1) = number_cells_per_voxel->at(voxel_index-1) + 1; } } } } // set the numberofcells to the correct value IntegerData *nc = (IntegerData*) db->getDataItem("numberofcells"); nc->setInteger(cell_positions->size()); this->cellnumber = cell_positions->size(); // initialise all the remaining vectors this->doTheRest(ag); }
int csdb_generator::read_from (const char *srcfile) { inf_ = new ifstream(srcfile); char *ptr; while (inf_->good() && !inf_->eof()) { linecounter_++; switch (read_line ()) { case -1: // bogus line fail ("unknown field tag"); break; case 0: // comment or blank line break; case 1: // start entry_.desc_ = 0; entry_.loc_name_ = 0; entry_.codeset_id_ = 0; entry_.num_sets_ = 0; entry_.max_bytes_ = 0; in_entry_ = 1; break; case 2: // end if (entry_.codeset_id_ == 0) fail ("entry missing rgy_value"); if (entry_.num_sets_ == 0) fail ("entry does not include at least one char_value"); if (entry_.max_bytes_ == 0) fail ("entry does not define max_bytes"); write_entry (); delete [] const_cast<char *> (entry_.desc_); delete [] const_cast<char *> (entry_.loc_name_); count_++; in_entry_ = 0; break; case 3: // description if (entry_.desc_ != 0) fail ("duplicate description"); entry_.desc_ = ACE_OS::strdup(line_data_); break; case 4: // loc_name if (entry_.loc_name_ != 0) fail ("duplicate loc_name"); entry_.loc_name_ = ACE_OS::strdup(line_data_); break; case 5: // rgy_value if (entry_.codeset_id_ != 0) fail ("duplicate rgy_value"); entry_.codeset_id_ = ACE_OS::strtoul(line_data_,&ptr,16); if (*ptr != 0 || entry_.codeset_id_ == 0) { char emsg [100]; ACE_OS::sprintf (emsg,"invalid rgy_value, '%s'",line_data_); fail (emsg); } break; case 6: // char_values if (entry_.num_sets_ != 0) fail ("duplicate char_values"); ptr = line_data_; do { if (*ptr == ':') ptr++; ACE_CDR::UShort tmp = static_cast<ACE_CDR::UShort> (ACE_OS::strtoul(ptr,&ptr,16)); if (*ptr != 0 && *ptr != ':') { char *emsg = new char [100]; ACE_OS::sprintf (emsg,"invalid symbol \'%c\' in char_values",*ptr); fail (emsg); } if (entry_.num_sets_ < max_charsets_) entry_.char_sets_[entry_.num_sets_++] = tmp; else entry_.num_sets_++; } while (*ptr == ':'); if (entry_.num_sets_ > max_charsets_) { char *emsg = new char [200]; ACE_OS::sprintf (emsg,"max of %d char_values exceeded.\nIncrease ACE_Codeset_Registry::max_charsets_ to at least %d and rebuild mkcsregdb",max_charsets_,entry_.num_sets_); fail (emsg); } break; case 7: // max_bytes if (entry_.max_bytes_ != 0) fail ("duplicate max_bytes"); entry_.max_bytes_ = static_cast<ACE_CDR::UShort> (ACE_OS::strtol(line_data_,&ptr,10)); if (*ptr != 0) fail ("invalid max_bytes"); break; } } return 0; }
void readSOFT(ifstream& input){ string BAM_line; string ori1,chr1,begin1,ori2,chr2,begin2, end1, end2, num_t; string ori1_t,chr1_t,begin1_t,ori2_t,chr2_t,begin2_t, end1_t, end2_t; int b, e; int flag=0; ofstream Out_SOFT("Only_SOFT"); while(!input.eof()){ getline(input, BAM_line); if(BAM_line.length()==0) //in case of a blank line break; istringstream ss(BAM_line); ss >> chr1_t >> begin1_t >> ori1_t >> chr2_t >> begin2_t >> ori2_t >> num_t; //ss >> ori1_t >> chr1_t >> begin1_t >> ori2_t >> chr2_t >> begin2_t >> name >> qua; if(chr1_t == chr2_t && atoi(begin1_t.c_str()) <= atoi(begin2_t.c_str()) || chr1_t < chr2_t){ ori1 = ori1_t; chr1 = chr1_t; begin1 = begin1_t; ori2 = ori2_t; chr2 = chr2_t; begin2 = begin2_t; } else{ ori1 = ori2_t; chr1 = chr2_t; begin1 = begin2_t; ori2 = ori1_t; chr2 = chr1_t; begin2 = begin1_t; } if(atoi(num_t.c_str()) < FINAL_SOFT_cut){ continue; } interval const*i1; interval const*i2; int flag_ = 0; // string tt_1 = chr1+"\t"+chr2+"\t"+ori1+"\t"+ori2; //string tt_1 = chr1+"\t"+chr2; //string tt_2 = chr2+"\t"+chr1; if(ori1 == "+"){ ori1 = "-"; } else{ ori1 = "+"; } if(ori2 == "+"){ ori2 = "-"; } else{ ori2 = "+"; } string tt_1 = chr1+"\t"+chr2+"\t"+ori1+"\t"+ori2; if(ori1 == "-"){ i1 = find_flag(all_bed_1[tt_1]["-"], atoi(begin1.c_str())+50, ori1); } else{ i1 = find_flag(all_bed_1[tt_1]["+"], atoi(begin1.c_str())-50,ori1); } if(ori2 == "-"){ i2 = find_flag(all_bed_2[tt_1]["-"], atoi(begin2.c_str())+50,ori2); } else{ i2 = find_flag(all_bed_2[tt_1]["+"], atoi(begin2.c_str())-50,ori2); } if(i1 != NULL && i2 != NULL){ set<interval>::iterator it_1, it_2; for(it_1 = all_bed_1[tt_1][ori1][(*i1)].begin(); it_1!= all_bed_1[tt_1][ori1][(*i1)].end(); it_1++){ for(it_2 = all_bed_2[tt_1][ori2][(*i2)].begin(); it_2!= all_bed_2[tt_1][ori2][(*i2)].end(); it_2++){ ostringstream key; key.clear(); key << chr1 << "\t" << (*it_1).start << "\t" << (*it_1).end << "\t" << ori1 << "\t" << chr2 << "\t" << (*it_2).start << "\t" << (*it_2).end << "\t" << ori2; if(ALL.find(key.str()) != ALL.end()){ int a,b,c,d; if(ori1 == "+"){ a = (*it_1).start; b = atoi(begin1.c_str()); } else{ a = atoi(begin1.c_str()); b = (*it_1).end; } if(ori2 == "+"){ c = (*it_2).start; d = atoi(begin2.c_str()); } else{ c = atoi(begin2.c_str()); d = (*it_2).end; } ostringstream key2; key2.clear(); key2 << chr1 << "\t" << a << "\t" << b << "\t" << ori1 << "\t" << chr2 << "\t" << c << "\t" << d << "\t" << ori2; ostringstream alt;//final format chr1 pos1 ori1 chr2 pos2 ori2 alt << chr1 << "\t"; if(ori1 == "+") alt << b; else alt << a; alt << "\t" << ori1 << "\t" << chr2 << "\t"; if(ori2 == "+") alt << d; else alt << c; alt << "\t" << ori2; cout << alt.str() << "\t" << ALL[key.str()] << "\t" << num_t << endl; STORE_PAIR[key.str()]=1; flag_ = 1; break; } } } } if(flag_ == 0 && atoi(num_t.c_str()) >= 5){ int a,b,c,d; if(ori1 == "+"){ b = atoi(begin1.c_str()); a = b - 50; } else{ a = atoi(begin1.c_str()); b = a + 50; } if(ori2 == "+"){ d = atoi(begin2.c_str()); c = d - 50; } else{ c = atoi(begin2.c_str()); d = c + 50; } ostringstream key2; key2.clear(); //key2 << chr1 << "\t" << a << "\t" << b << "\t" << ori1 << "\t" << chr2 << "\t" << c << "\t" << d << "\t" << ori2; //Out_SOFT << key2.str() << "\t0\t" << num_t << endl; Out_SOFT << chr1 << "\t" << begin1 << "\t" << ori1 << "\t" << chr2 << "\t" << begin2 << "\t" << ori2 << "\t0\t" << num_t << endl; } } }
//-------------------------------------------------------------------- bool TFEMParams::read(ifstream& in) { unsigned len, size; char* str; string key; Float value; // Тип задачи in.read((char*)&fType,sizeof(FEMType)); // Метод решения СЛАУ in.read((char*)&sMethod,sizeof(SolveMethod)); // Способ аппроксимации по времени in.read((char*)&tMethod,sizeof(TimeMethod)); // Метод решения упруго-пластических задач in.read((char*)&pMethod,sizeof(PlasticityMethod)); // Погрешность расчета in.read((char*)&eps,sizeof(Float)); // Ширина вывода in.read((char*)&width,sizeof(unsigned)); // Точность ... in.read((char*)&precision,sizeof(unsigned)); // Упругие параметры in.read((char*)&len,sizeof(unsigned)); if (len) { e.resize(len); for (unsigned i = 0; i < len; i++) in.read((char*)&e[i],sizeof(Float)); } in.read((char*)&len,sizeof(unsigned)); if (len) { m.resize(len); for (unsigned i = 0; i < len; i++) in.read((char*)&m[i],sizeof(Float)); } // Шаг по нагрузке in.read((char*)&forceStep,sizeof(Float)); // Механические свойства материала in.read((char*)&len,sizeof(unsigned)); if (len) { s.resize(len); for (unsigned i = 0; i < len; i++) in.read((char*)&s[i],sizeof(Float)); } in.read((char*)&len,sizeof(unsigned)); if (len) { d.resize(len); for (unsigned i = 0; i < len; i++) in.read((char*)&d[i],sizeof(Float)); } // Плотность и демпфирование in.read((char*)&density,sizeof(Float)); in.read((char*)&damping,sizeof(Float)); // Начальные условия in.read((char*)&t0,sizeof(Float)); in.read((char*)&t1,sizeof(Float)); in.read((char*)&th,sizeof(Float)); // Функции for (unsigned i = 0; i < funName.size(); i++) { in.read((char*)&len,sizeof(unsigned)); str = new char[len]; in.read((char*)str,len*sizeof(char)); funName[i] = str; delete [] str; } // Краевые условия и нагрузки bc.read(in); // Вспомогательные параметры variables.clear(); in.read((char*)&size,sizeof(unsigned)); for (unsigned i = 0; i < size; i++) { in.read((char*)&len,sizeof(unsigned)); if (len) { str = new char[len]; in.read((char*)str,len*sizeof(char)); key = str; delete [] str; } else continue; in.read((char*)&value,sizeof(Float)); variables[key] = value; } // Параметры температурного расширения in.read((char*)&alpha,sizeof(Float)); in.read((char*)&dT,sizeof(Float)); return !in.fail(); }
~Iterator() { plik.close(); }
Iterator(const char* nazwa) { plik.open(nazwa); next(); }
//--------------------------------------------------- //setData //set data of the book using the file input //@param infile the input file void Periodical::setData(ifstream& infile){ infile.get(); getline(infile, thisBookTitle, ','); infile >> month >> year; }
bool CLevel::LoadVersion1( ifstream& File ) { bool StopReadingFile = false; filebuf *pbuf = File.rdbuf(); // go to the beginning pbuf->pubseekpos (0,ios::in); // For each line of characters to read for (int y = 0 ; y < ARENA_HEIGHT ; y++) { // Buffer where we'll store one line of characters. We'll read the two EOL characters as well. string Line; int ReadBytes; // Read one line of characters (including the EOL chars) if (File.good()) { getline( File, Line ); ReadBytes = Line.size(); } else { ReadBytes = 0; } // Check if all the characters were read if (ReadBytes < ARENA_WIDTH) { // Log there is a problem theLog.WriteLine ("Options => !!! Level file is incorrect (Line: %d, Length: %d).", y+1, ReadBytes); // Close the level file File.close(); // Stop loading levels StopReadingFile = true; break; } // For each character representing a block in this line for (int x = 0 ; x < ARENA_WIDTH ; x++) { // According to the character value, store the corresponding block type in the current position and level switch(Line.c_str()[x]) { case '*' : m_ArenaData[x][y] = BLOCKTYPE_HARDWALL; break; case '-' : m_ArenaData[x][y] = BLOCKTYPE_RANDOM; break; case ' ' : m_ArenaData[x][y] = BLOCKTYPE_FREE; break; case '1' : m_ArenaData[x][y] = BLOCKTYPE_WHITEBOMBER; break; case '2' : m_ArenaData[x][y] = BLOCKTYPE_BLACKBOMBER; break; case '3' : m_ArenaData[x][y] = BLOCKTYPE_REDBOMBER; break; case '4' : m_ArenaData[x][y] = BLOCKTYPE_BLUEBOMBER; break; case '5' : m_ArenaData[x][y] = BLOCKTYPE_GREENBOMBER; break; case 'R' : m_ArenaData[x][y] = BLOCKTYPE_MOVEBOMB_RIGHT; break; case 'D' : m_ArenaData[x][y] = BLOCKTYPE_MOVEBOMB_DOWN; break; case 'L' : m_ArenaData[x][y] = BLOCKTYPE_MOVEBOMB_LEFT; break; case 'U' : m_ArenaData[x][y] = BLOCKTYPE_MOVEBOMB_UP; break; default : { // Log there is a problem theLog.WriteLine ("Options => !!! Level file is incorrect (unknown character %c).", Line[x]); // Close the level file File.close(); // Stop loading levels StopReadingFile = true; break; } } } // If there was a problem if (StopReadingFile) { // Stop reading this level file break; } } m_NumberOfItemsInWalls[ITEM_BOMB] = INITIAL_ITEMBOMB; m_NumberOfItemsInWalls[ITEM_FLAME] = INITIAL_ITEMFLAME; m_NumberOfItemsInWalls[ITEM_KICK] = INITIAL_ITEMKICK; m_NumberOfItemsInWalls[ITEM_ROLLER] = INITIAL_ITEMROLLER; m_NumberOfItemsInWalls[ITEM_SKULL] = INITIAL_ITEMSKULL; m_NumberOfItemsInWalls[ITEM_THROW] = INITIAL_ITEMTHROW; m_NumberOfItemsInWalls[ITEM_PUNCH] = INITIAL_ITEMPUNCH; m_NumberOfItemsInWalls[ITEM_REMOTE] = INITIAL_ITEMREMOTE; m_InitialBomberSkills[ BOMBERSKILL_FLAME ] = INITIAL_FLAMESIZE; m_InitialBomberSkills[ BOMBERSKILL_BOMBS ] = INITIAL_BOMBS; m_InitialBomberSkills[ BOMBERSKILL_BOMBITEMS ] = 0; m_InitialBomberSkills[ BOMBERSKILL_FLAMEITEMS ] = 0; m_InitialBomberSkills[ BOMBERSKILL_ROLLERITEMS ] = 0; m_InitialBomberSkills[ BOMBERSKILL_KICKITEMS ] = 0; m_InitialBomberSkills[ BOMBERSKILL_THROWITEMS ] = 0; m_InitialBomberSkills[ BOMBERSKILL_PUNCHITEMS ] = 0; m_InitialBomberSkills[ BOMBERSKILL_REMOTEITEMS ] = 0; return !StopReadingFile; }
int TFoul::load( ifstream &ifs, vector<TPlayer*> &HomePlayer, vector<TPlayer*> &GuestPlayer ) { unsigned int i; string line; while(ifs.good()) { line = TTools::ReadUnspaced(ifs); if ( TTools::strcontain( line,"</Foul>" ) ) { #ifdef DEBUG cout << line << endl; #endif return 1; } else if( TTools::strcontain( line,"<MinuteOfPlay>" ) ) { #ifdef DEBUG cout << line << endl; #endif std::string tag1 = "<MinuteOfPlay>",tag2 = "</MinuteOfPlay>"; line = TTools::tagremove(line, tag1); line = TTools::tagremove(line, tag2); TEvent::SetMinuteOfPlay( atoi(line.c_str()) ); } else if ( TTools::strcontain(line,"PlayerTricotNr" ) ) { #ifdef DEBUG cout << line << endl; #endif vector<TPlayer*> Player = GuestPlayer; string S_Team = "Guest"; /* "Guest" or "Home" */ string S_Fouled = ""; /* Fouled or "" */ if ( TTools::strcontain(line,"PlayerTricotNr Team=\"Home\">" ) ) /* Home: TFoul or TEvent player */ { Player = HomePlayer; S_Team = "Home"; } if ( TTools::strcontain(line,"<FouledPlayerTricotNr Team=" ) ) S_Fouled = "Fouled"; std::string tag1 = "<"+S_Fouled+"PlayerTricotNr Team=\""+S_Team+"\">",tag2 = "</"+S_Fouled+"PlayerTricotNr>"; //cout << "Reconstructed Tag1: " << tag1 << endl; line = TTools::tagremove(line, tag1); line = TTools::tagremove(line, tag2); /* add correct player to vector, check tricot numbers :) push_back */ for ( i = 0; i < Player.size(); i++ ) { //cout << "Nr: " << i << " " << S_Team << " " << S_Fouled << "Tricot Nr.: " << Player.at(i)->GettricotNr() << endl; if( Player.at(i)->GettricotNr() == atoi(line.c_str()) ) { //cout << "Found nr.: " << Player.at(i)->GettricotNr() << endl; if ( S_Fouled == "Fouled" ) { FouledPlayer = Player.at(i); #ifdef DEBUG cout << "Added " << S_Team << " player to TFoul: "<< FouledPlayer->Getname() << " Nr.: " << FouledPlayer->GettricotNr() << endl; #endif } else { TEvent::SetPlayer( Player.at(i) ); #ifdef DEBUG cout << "Added " << S_Team << " player to TEvent from TFoul: "<< TEvent::GetPlayer()->Getname() << " Nr.: " << TEvent::GetPlayer()->GettricotNr() << endl; #endif } break; } } } } return 0; }
void main(unsigned int count,char **arg) { unsigned long x=0,y=0,f; short temp[4]; printf ("\nxbooxp v1.2, GBA multiboot transfer software designed for Windows XP/2000.\nCopyright 2005 by Vishnu.\n\n"); BeginTransfer(); if (count<2) Usage(arg[0]); if (count>6) { printf ("Too many arguments.....Read intructions more carefully.\n\n"); QuitProgram(); } else { for (x=1; x<=(count-1) ;x++) //Argument Check loop { if (arg[x][0]=='-') //first check for - { if (arg[x][1]=='h') //checking for -h no_header=1; else if (arg[x][1]=='d') //checking for -d { if ((arg[x][2]>='1')&&(arg[x][2]<='9')) { bit_delay = (arg[x][2]-48); //offset bit delay unit_delay = unit_delay+(3*(arg[x][2]-48)); } else { printf ("Invalid argument %s, if delay=1 then type -d1.\n\n",arg[x]); QuitProgram(); } } else if (arg[x][1]=='p') //checking for -p { for (y=0; y<3; y++) { if ((arg[x][y+2]>='0')&&(arg[x][y+2]<='9')) temp[y]=arg[x][y+2]-48; else if ((arg[x][y+2]>='A')&&(arg[x][y+2]<='F')) temp[y]=arg[x][y+2]-55; else { printf ("Invalid port address %s\nIf your port address is 0x278, then type -p278.\n\n",arg[x]); QuitProgram(); } } port_address=(temp[0]<<8)+(temp[1]<<4)+temp[2]; } else if (arg[x][1]=='t') //checking for -t test_flag=1; else { printf ("Invalid argument %s\n\n",arg[x]); QuitProgram(); } } else if (filename==0) //Second Check for file.name { f=x; filename=1; } else //Else is garbage { printf ("Invalid command %s\n\n",arg[x]); QuitProgram(); } } if (filename==0) //If no file name { printf ("No file specified.....\n\n"); QuitProgram(); } else if (filename==1) //If file name exists, then... { game.open(arg[f], ios::in | ios::binary); if (game.fail()) { printf ("Error opening file %s\n\n",arg[f]); QuitProgram(); } } } //printf ("Header=%d, bit delay=%.3f, unit delay=%.3f, Port=%X, File=%s\n\n",no_header,bit_delay,unit_delay,port_address,arg[f]); FileCalc(); Initialize(); SendMainData(); UnloadIODLL(); }
void Labeler::readWordEmbeddings(const string& inFile, NRMat<double>& wordEmb) { static ifstream inf; if (inf.is_open()) { inf.close(); inf.clear(); } inf.open(inFile.c_str()); static string strLine, curWord; static int wordId; //find the first line, decide the wordDim; while (1) { if (!my_getline(inf, strLine)) { break; } if (!strLine.empty()) break; } int unknownId = m_wordAlphabet.from_string(unknownkey); static vector<string> vecInfo; split_bychar(strLine, vecInfo, ' '); int wordDim = vecInfo.size() - 1; std::cout << "word embedding dim is " << wordDim << std::endl; m_options.wordEmbSize = wordDim; wordEmb.resize(m_wordAlphabet.size(), wordDim); wordEmb = 0.0; curWord = normalize_to_lowerwithdigit(vecInfo[0]); wordId = m_wordAlphabet.from_string(curWord); hash_set<int> indexers; double sum[wordDim]; int count = 0; bool bHasUnknown = false; if (wordId >= 0) { count++; if (unknownId == wordId) bHasUnknown = true; indexers.insert(wordId); for (int idx = 0; idx < wordDim; idx++) { double curValue = atof(vecInfo[idx + 1].c_str()); sum[idx] = curValue; wordEmb[wordId][idx] = curValue; } } else { for (int idx = 0; idx < wordDim; idx++) { sum[idx] = 0.0; } } while (1) { if (!my_getline(inf, strLine)) { break; } if (strLine.empty()) continue; split_bychar(strLine, vecInfo, ' '); if (vecInfo.size() != wordDim + 1) { std::cout << "error embedding file" << std::endl; } curWord = normalize_to_lowerwithdigit(vecInfo[0]); wordId = m_wordAlphabet.from_string(curWord); if (wordId >= 0) { count++; if (unknownId == wordId) bHasUnknown = true; indexers.insert(wordId); for (int idx = 0; idx < wordDim; idx++) { double curValue = atof(vecInfo[idx + 1].c_str()); sum[idx] = curValue; wordEmb[wordId][idx] += curValue; } } } if (!bHasUnknown) { for (int idx = 0; idx < wordDim; idx++) { wordEmb[unknownId][idx] = sum[idx] / count; } count++; std::cout << unknownkey << " not found, using averaged value to initialize." << std::endl; } int oovWords = 0; int totalWords = 0; for (int id = 0; id < m_wordAlphabet.size(); id++) { if (indexers.find(id) == indexers.end()) { oovWords++; for (int idx = 0; idx < wordDim; idx++) { wordEmb[id][idx] = wordEmb[unknownId][idx]; } } totalWords++; } std::cout << "OOV num is " << oovWords << ", total num is " << m_wordAlphabet.size() << ", embedding oov ratio is " << oovWords * 1.0 / m_wordAlphabet.size() << std::endl; }
void operator ()(ifstream& f) { if (!f.is_open()) { throw contract_exception(); } }
bool openFile(ifstream & stream, string filename) { stream.clear(); stream.open(expandPathname(filename).c_str()); return !stream.fail(); }
/************************************************************************************************* map<string, int> Bayesian::parseTaxMap(string newTax) { try{ map<string, int> parsed; newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';' //parse taxonomy string individual; while (newTax.find_first_of(';') != -1) { individual = newTax.substr(0,newTax.find_first_of(';')); newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length()); parsed[individual] = 1; } //get last one parsed[newTax] = 1; return parsed; } catch(exception& e) { m->errorOut(e, "Bayesian", "parseTax"); exit(1); } } **************************************************************************************************/ void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) { try{ #ifdef USE_MPI int pid, num, num2, processors; vector<unsigned long long> positions; vector<unsigned long long> positions2; MPI_Status status; MPI_File inMPI; MPI_File inMPI2; MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are MPI_Comm_size(MPI_COMM_WORLD, &processors); int tag = 2001; char inFileName[1024]; strcpy(inFileName, inNumName.c_str()); char inFileName2[1024]; strcpy(inFileName2, inName.c_str()); MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer MPI_File_open(MPI_COMM_WORLD, inFileName2, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI2); //comm, filename, mode, info, filepointer if (pid == 0) { positions = m->setFilePosEachLine(inNumName, num); positions2 = m->setFilePosEachLine(inName, num2); for(int i = 1; i < processors; i++) { MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD); MPI_Send(&positions[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD); MPI_Send(&num2, 1, MPI_INT, i, tag, MPI_COMM_WORLD); MPI_Send(&positions2[0], (num2+1), MPI_LONG, i, tag, MPI_COMM_WORLD); } }else{ MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status); positions.resize(num+1); MPI_Recv(&positions[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status); MPI_Recv(&num2, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status); positions2.resize(num2+1); MPI_Recv(&positions2[0], (num2+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status); } //read version int length = positions2[1] - positions2[0]; char* buf5 = new char[length]; MPI_File_read_at(inMPI2, positions2[0], buf5, length, MPI_CHAR, &status); delete buf5; //read numKmers length = positions2[2] - positions2[1]; char* buf = new char[length]; MPI_File_read_at(inMPI2, positions2[1], buf, length, MPI_CHAR, &status); string tempBuf = buf; if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); } delete buf; istringstream iss (tempBuf,istringstream::in); iss >> numKmers; //initialze probabilities wordGenusProb.resize(numKmers); for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); } int kmer, name; vector<int> numbers; numbers.resize(numKmers); float prob; vector<float> zeroCountProb; zeroCountProb.resize(numKmers); WordPairDiffArr.resize(numKmers); //read version length = positions[1] - positions[0]; char* buf6 = new char[length]; MPI_File_read_at(inMPI2, positions[0], buf6, length, MPI_CHAR, &status); delete buf6; //read file for(int i=1;i<num;i++){ //read next sequence length = positions[i+1] - positions[i]; char* buf4 = new char[length]; MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status); tempBuf = buf4; if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); } delete buf4; istringstream iss (tempBuf,istringstream::in); float probTemp; iss >> zeroCountProb[i] >> numbers[i] >> probTemp; WordPairDiffArr[i].prob = probTemp; } MPI_File_close(&inMPI); for(int i=2;i<num2;i++){ //read next sequence length = positions2[i+1] - positions2[i]; char* buf4 = new char[length]; MPI_File_read_at(inMPI2, positions2[i], buf4, length, MPI_CHAR, &status); tempBuf = buf4; if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); } delete buf4; istringstream iss (tempBuf,istringstream::in); iss >> kmer; //set them all to zero value for (int i = 0; i < genusNodes.size(); i++) { wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1)); } //get probs for nonzero values for (int i = 0; i < numbers[kmer]; i++) { iss >> name >> prob; wordGenusProb[kmer][name] = prob; } } MPI_File_close(&inMPI2); MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case #else //read version string line = m->getline(in); m->gobble(in); in >> numKmers; m->gobble(in); //cout << threadID << '\t' << line << '\t' << numKmers << &in << '\t' << &inNum << '\t' << genusNodes.size() << endl; //initialze probabilities wordGenusProb.resize(numKmers); for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); } int kmer, name, count; count = 0; vector<int> num; num.resize(numKmers); float prob; vector<float> zeroCountProb; zeroCountProb.resize(numKmers); WordPairDiffArr.resize(numKmers); //read version string line2 = m->getline(inNum); m->gobble(inNum); float probTemp; //cout << threadID << '\t' << line2 << '\t' << this << endl; while (inNum) { inNum >> zeroCountProb[count] >> num[count] >> probTemp; WordPairDiffArr[count].prob = probTemp; count++; m->gobble(inNum); //cout << threadID << '\t' << count << endl; } inNum.close(); //cout << threadID << '\t' << "here1 " << &wordGenusProb << '\t' << &num << endl; // //cout << threadID << '\t' << &genusTotals << '\t' << endl; //cout << threadID << '\t' << genusNodes.size() << endl; while(in) { in >> kmer; //cout << threadID << '\t' << kmer << endl; //set them all to zero value for (int i = 0; i < genusNodes.size(); i++) { wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1)); } //cout << threadID << '\t' << num[kmer] << "here" << endl; //get probs for nonzero values for (int i = 0; i < num[kmer]; i++) { in >> name >> prob; wordGenusProb[kmer][name] = prob; } m->gobble(in); } in.close(); //cout << threadID << '\t' << "here" << endl; #endif } catch(exception& e) { m->errorOut(e, "Bayesian", "readProbFile"); exit(1); } }
int main() { cin.getline(s, 100002); for(int i=0; s[i] ; ) { if(isdigit(s[i])) { fac[++vf]=s[i]-'0'; while(isdigit(s[++i])) fac[vf]=fac[vf]*10+s[i]-'0'; continue; } if(s[i]=='(') { op[++kp]=s[i]; i++; continue; } if(s[i]=='*') { //equal priority if(op[kp]=='*') { kp--; op1=fac[vf--]; fac[vf]*=op1; } if(op[kp]=='/') { kp--; op1=fac[vf--]; fac[vf]/=op1; } else op[kp]=s[i]; } if(s[i]=='/') { if(op[kp]=='*') { kp--; op1=fac[vf--]; fac[vf]*=op1; } if(op[kp]=='/') { kp--; op1=fac[vf--]; fac[vf]/=op1; } else op[kp]=s[i]; } if(s[i]=='+') { if(op[kp]=='+') { kp--; op1=fac[vf--]; fac[vf]+=op1; } if(op[kp]=='-') { kp--; op1=fac[vf--]; fac[vf]-=op1; } if(op[kp]=='*') { op1=fac[vf--]; fac[vf]*=op1; } else if(op[kp]=='/') { op1=fac[vf--]; fac[vf]/=op1; } else op[kp]=s[i]; i++ ;continue; } if(s[i]=='-') { if(op[kp]=='+') { kp--; op1=fac[vf--]; fac[vf]+=op1; } if(op[kp]=='-') { kp--; op1=fac[vf--]; fac[vf]-=op1; } if(op[kp]=='*') { op1=fac[vf--]; fac[vf]*=op1; } else if(op[kp]=='/') { op1=fac[vf--]; fac[vf]/=op1; } else op[kp]=s[i]; i++ ;continue; } if(s[i]==')') { if(op[kp]=='(') { kp--; ++i; continue; } else if(op[kp]=='*') { op1=fac[vf--]; fac[vf]*=op1; --kp; } else if(op[kp]=='/') { op1=fac[vf--]; fac[vf]/=op1; --kp; } else if(op[kp]=='+') { op1=fac[vf--]; fac[vf]+=op1; --kp; } else if(op[kp]=='-') { op1=fac[vf--]; fac[vf]-=op1; --kp; } } ++i; } // for(int i=1;i<=kp;++i) // cout<<op[i]; cout<<fac[1]; cin.close(); cout.close(); return 0; }
void closeFile() { if(file.is_open()) file.close(); }
void parsefile(ifstream &file, ifstream &file2, ifstream &file3,ifstream &file4, ifstream &file5){ for (int i=0; i<600; i++) { for(int j=0; j<600; j++){ zbuffer[i][j] = std::numeric_limits<int>::min(); } } double Ax; double Ay; double Az; double Atexturex; double Atexturey; double Avecteurx; double Avecteury; double Avecteurz; double Bx; double By; double Bz; double Btexturex; double Btexturey; double Bvecteurx; double Bvecteury; double Bvecteurz; double Cx; double Cy; double Cz; double Ctexturex; double Ctexturey; double Cvecteurx; double Cvecteury; double Cvecteurz; file.open("african_head.obj"); file2.open("african_head.obj"); file3.open("african_head.obj"); file4.open("african_head.obj"); getLineCoordV(file); getLineCoordVt(file3); getLineCoordVn(file4); int nombre1; int nombre2; int nombre3; int nombre1vt; int nombre2vt; int nombre3vt; int nombre1vn; int nombre2vn; int nombre3vn; std::string myString; while (!file2.eof()) { getline(file2, myString); if ((myString[0] == 'f') && (myString[1] == ' ')) { myString.erase(myString.begin(),myString.begin()+2); int i = 0; while (myString[i] == ' ') { i++; } while (myString[i] != '/') { char c = myString[i]; // PREMIER SOMMET sommet1.push_back(c); i++; } i++; while (myString[i] != '/') { char c = myString[i]; // Texture PREMIER SOMMET couleursommet1.push_back(c); i++; } i++; while (myString[i] != ' ') { char c = myString[i]; // Vecteur PREMIER SOMMET vecteursommet1.push_back(c); i++; } while (myString[i] == ' ') { i++; } while (myString[i] != '/') { char c = myString[i]; // DEUXIEME SOMMET sommet2.push_back(c); i++; } i++; while (myString[i] != '/') { char c = myString[i]; // texture DEUXIEME SOMMET couleursommet2.push_back(c); i++; } i++; while (myString[i] != ' ') { char c = myString[i]; // Vecteur DEUXIEME SOMMET vecteursommet2.push_back(c); i++; } while (myString[i] == ' ') { i++; } while (myString[i] != '/') { char c = myString[i]; // Troisieme SOMMET sommet3.push_back(c); i++; } i++; while (myString[i] != '/') { char c = myString[i]; // texture Troisieme SOMMET couleursommet3.push_back(c); i++; }i++; while (myString[i] != ' ') { char c = myString[i]; // Vecteur TROISIEME SOMMET vecteursommet3.push_back(c); i++; } std::string strx(sommet1.begin(), sommet1.end()); std::string stry(sommet2.begin(), sommet2.end()); std::string strz(sommet3.begin(), sommet3.end()); std::string strvtx(couleursommet1.begin(), couleursommet1.end()); std::string strvty(couleursommet2.begin(), couleursommet2.end()); std::string strvtz(couleursommet3.begin(), couleursommet3.end()); std::string strvnx(vecteursommet1.begin(), vecteursommet1.end()); std::string strvny(vecteursommet2.begin(), vecteursommet2.end()); std::string strvnz(vecteursommet3.begin(), vecteursommet3.end()); std::istringstream isstx(strvtx); std::istringstream issty(strvty); std::istringstream isstz(strvtz); std::istringstream issx(strx); std::istringstream issy(stry); std::istringstream issz(strz); std::istringstream issnx(strvnx); std::istringstream issny(strvny); std::istringstream issnz(strvnz); issx >> nombre1; issy >> nombre2; issz >> nombre3; isstx >> nombre1vt; issty >> nombre2vt; isstz >> nombre3vt; issnx >> nombre1vn; issny >> nombre2vn; issnz >> nombre3vn; Ax = taballv[nombre1-1][0]; Ay = taballv[nombre1-1][1]; Az = taballv[nombre1-1][2]; Atexturex = taballvt[nombre1vt-1][0]; Atexturey = taballvt[nombre1vt-1][1]; Avecteurx = taballvn[nombre1vn-1][0]; Avecteury = taballvn[nombre1vn-1][1]; Avecteurz = taballvn[nombre1vn-1][2]; Bx = taballv[nombre2-1][0]; By = taballv[nombre2-1][1]; Bz = taballv[nombre2-1][2]; Btexturex = taballvt[nombre2vt-1][0]; Btexturey = taballvt[nombre2vt-1][1]; Bvecteurx = taballvn[nombre2vn-1][0]; Bvecteury = taballvn[nombre2vn-1][1]; Bvecteurz = taballvn[nombre2vn-1][2]; Cx = taballv[nombre3-1][0]; Cy = taballv[nombre3-1][1]; Cz = taballv[nombre3-1][2]; Ctexturex = taballvt[nombre3vt-1][0]; Ctexturey = taballvt[nombre3vt-1][1]; Cvecteurx = taballvn[nombre3vn-1][0]; Cvecteury = taballvn[nombre3vn-1][1]; Cvecteurz = taballvn[nombre3vn-1][2]; barycentricFullMethod(Ax, Ay, Az, Bx, By, Bz, Cx, Cy, Cz, Atexturex, Atexturey, Btexturex, Btexturey, Ctexturex, Ctexturey, Avecteurx, Avecteury, Avecteurz, Bvecteurx, Bvecteury, Bvecteurz, Cvecteurx, Cvecteury, Cvecteurz, zbuffer); sommet1.clear(); sommet2.clear(); sommet3.clear(); couleursommet1.clear(); couleursommet2.clear(); couleursommet3.clear(); vecteursommet1.clear(); vecteursommet2.clear(); vecteursommet3.clear(); } }
void load(ifstream &f,mint &elementos, mdouble &nodos, mdouble &contorno){ nodos.clear(); elementos.clear(); contorno.clear(); /// VARIABLES int n,o,p; char t[100]; double x; /// CARGAMOS LAS VARIABLES GENERALES DEL PROBLEMA f.getline(t,100); e = atof(t); /// TOLERANCIA f.getline(t,100); iteraciones = atoi(t); /// ITERACIONES MAXIMAS f.getline(t,100); dt = atof(t); /// PASO DE TIEMPO f.getline(t,100); Re = atof(t); /// NUMERO DE REYNOLDS /// LEEMOS LA CANTIDAD DE NODOS f.getline(t,100); n = atoi(t); /// ASIGNAMOS LOS NODOS for(int i=0;i<n;i++){ vector<double> nod; /// COORDENADA X f.getline(t,100); x = atof(t); nod.push_back(x); /// COORDENADA Y f.getline(t,100); x = atof(t); nod.push_back(x); nodos.push_back(nod); } /// LEEMOS LA CANTIDAD DE ELEMENTOS f.getline(t,100); n = atoi(t); /// LEEMOS LA CANTIDAD DE NODOS POR ELEMENTO f.getline(t,100); o = atoi(t); /// LEEMOS LOS INDICES DE LOS ELEMENTOS for(int i=0;i<n;i++){ vector<int> e; f.getline(t,100); char *ptr; /// LOS NUMEROS DE LOS NODOS ESTAN SEPARADOS POR UN ESPACIO ptr = strtok(t," "); p = atoi(ptr); e.push_back(p-1); for(int j=0;j<o-1;j++){ // mandarle un null parece que hace que continue con el puntero del anterior strtok ptr = strtok(NULL," "); p = atoi(ptr); e.push_back(p-1); } elementos.push_back(e); } /// LEEMOS LAS CONDICIONES DE CONTORNO /// LA ORGANIZACION DEL CONTORNO ES /// NumNodo TipoFront Valores /// LEEMOS LA CANTIDAD DE NODOS CON WALL f.getline(t,100); n = atoi(t); for(int i=0;i<n;i++){ vector<double> nContorno; /// NODO 1 f.getline(t,100); nContorno.push_back(atoi(t)-1); /// NODO 2 f.getline(t,100); nContorno.push_back(atoi(t)-1); /// TIPO DE CONTORNO nContorno.push_back(1.0); /// ASIGNAMOS u = v = 0 porque es wall nContorno.push_back(.0); nContorno.push_back(.0); contorno.push_back(nContorno); } /// LEEMOS LA CANTIDAD DE NODOS CON VELOCIDAD IMPUESTA f.getline(t,100); n = atoi(t); for(int i=0;i<n;i++){ vector<double> nContorno; /// NODO 1 f.getline(t,100); nContorno.push_back(atoi(t)-1); /// NODO 2 f.getline(t,100); nContorno.push_back(atoi(t)-1); /// TIPO DE CONTORNO nContorno.push_back(1.0); /// LEEMOS u f.getline(t,100); nContorno.push_back(atof(t)); /// LEEMOS v f.getline(t,100); nContorno.push_back(atof(t)); contorno.push_back(nContorno); } /// LEEMOS LA CANTIDAD DE NODOS CON PRESION IMPUESTA f.getline(t,100); n = atoi(t); for(int i=0;i<n;i++){ vector<double> nContorno; /// NODO 1 f.getline(t,100); nContorno.push_back(atof(t)-1); /// NODO 2 f.getline(t,100); nContorno.push_back(atof(t)-1); /// TIPO DE CONTORNO nContorno.push_back(2.0); /// LEEMOS LA PRESION f.getline(t,100); nContorno.push_back(atof(t)); contorno.push_back(nContorno); } f.close(); }
bool Map::loadMap(FILE *fp) { //#ifndef INVERSEXY ////#warning Map files do not work without inverted XY // return(false); //#endif if(!useNewMapFile){ mapHeader head; if(fread(&head, sizeof(head), 1, fp) != 1) { //map read error. return(false); } if(head.version != MAP_VERSION) { //invalid version... if there really are multiple versions, //a conversion routine could be possible. printf("Invalid map version 0x%lx\n", head.version); return(false); } if(createNewMapFile){ myfile<<"Version: "<<head.version<<endl; myfile<<"Faces: "<<head.face_count<<endl; myfile<<"Nodes: "<<head.node_count<<endl; myfile<<"Facelists: "<<head.facelist_count<<endl; } printf("Map header: %lu faces, %u nodes, %lu facelists\n", head.face_count, head.node_count, head.facelist_count); m_Faces = head.face_count; m_Nodes = head.node_count; m_FaceLists = head.facelist_count; /*fread(&m_Vertex, 4, 1, fp); fread(&m_Faces , 4, 1, fp);*/ //mFinalVertex = new VERTEX[m_Vertex]; mFinalFaces = new FACE [m_Faces]; mNodes = new NODE[m_Nodes]; mFaceLists = new unsigned long[m_FaceLists]; //fread(mFinalVertex, m_Vertex, sizeof(VERTEX), fp); unsigned long count; if((count=fread(mFinalFaces, sizeof(FACE), m_Faces , fp)) != m_Faces) { printf("Unable to read %lu faces from map file, got %lu.\n", m_Faces, count); return(false); } if(fread(mNodes, sizeof(NODE), m_Nodes, fp) != m_Nodes) { printf("Unable to read %lu faces from map file.\n", m_Nodes); return(false); } if(fread(mFaceLists, sizeof(unsigned long), m_FaceLists, fp) != m_FaceLists) { printf("Unable to read %lu faces from map file.\n", m_FaceLists); return(false); } unsigned long i; float v; for(i = 0; i < m_Faces; i++) { v = Vmax3(x, mFinalFaces[i].a, mFinalFaces[i].b, mFinalFaces[i].c); if(v > _maxx) _maxx = v; v = Vmin3(x, mFinalFaces[i].a, mFinalFaces[i].b, mFinalFaces[i].c); if(v < _minx) _minx = v; v = Vmax3(y, mFinalFaces[i].a, mFinalFaces[i].b, mFinalFaces[i].c); if(v > _maxy) _maxy = v; v = Vmin3(y, mFinalFaces[i].a, mFinalFaces[i].b, mFinalFaces[i].c); if(v < _miny) _miny = v; v = Vmax3(z, mFinalFaces[i].a, mFinalFaces[i].b, mFinalFaces[i].c); if(v > _maxz) _maxz = v; v = Vmin3(z, mFinalFaces[i].a, mFinalFaces[i].b, mFinalFaces[i].c); if(v < _minz) _minz = v; } if(createNewMapFile){ myfile<<"<MapCoords>"<<endl; myfile<<" <MaxX> "<<_maxx<<endl; myfile<<" <MinX> "<<_minx<<endl; myfile<<" <MaxY> "<<_maxy<<endl; myfile<<" <MinY> "<<_miny<<endl; myfile<<" <MaxZ> "<<_maxz<<endl; myfile<<" <MinZ> "<<_minz<<endl; myfile<<"</MapCoords>"<<endl; for(i = 0; i < m_Faces; i++) { myfile<<"<Face> "<<i<<endl; myfile<<" <LocA> "<<mFinalFaces[i].a.x<<" "<<mFinalFaces[i].a.y<<" "<<mFinalFaces[i].a.z<<endl; myfile<<" <LocB> "<<mFinalFaces[i].b.x<<" "<<mFinalFaces[i].b.y<<" "<<mFinalFaces[i].b.z<<endl; myfile<<" <LocC> "<<mFinalFaces[i].c.x<<" "<<mFinalFaces[i].c.y<<" "<<mFinalFaces[i].c.z<<endl; myfile<<" <Devi> "<<mFinalFaces[i].nx<<" "<<mFinalFaces[i].ny<<" "<<mFinalFaces[i].nz<<" "<<mFinalFaces[i].nd<<endl; myfile<<"</Face>"<<endl; _3dgraphfile<<mFinalFaces[i].a.x<<","<<mFinalFaces[i].a.y<<","<<mFinalFaces[i].a.z<<endl; _3dgraphfile<<mFinalFaces[i].b.x<<","<<mFinalFaces[i].b.y<<","<<mFinalFaces[i].b.z<<endl; _3dgraphfile<<mFinalFaces[i].c.x<<","<<mFinalFaces[i].c.y<<","<<mFinalFaces[i].c.z<<endl; } for(i = 0; i < m_Nodes; i++){ myfile<<"<Node> "<<i<<endl; myfile<<" <MaxX> "<<mNodes[i].maxx<<endl; myfile<<" <MinX> "<<mNodes[i].minx<<endl; myfile<<" <MaxY> "<<mNodes[i].maxy<<endl; myfile<<" <MinY> "<<mNodes[i].miny<<endl; myfile<<" <Flag> "<<int(mNodes[i].flags)<<endl; for(int k = 0; k < 4; k++) myfile<<" <Nodes> "<<mNodes[i].nodes[k]<<endl; myfile<<" <count> "<<mNodes[i].faces.count<<endl; myfile<<" <offset> "<<mNodes[i].faces.offset<<endl; myfile<<"</Node>"<<endl; } for(i = 0; i < m_FaceLists; i++){ myfile<<"<FaceList> "<<i<<endl; myfile<<" <Data> "<<mFaceLists[i]<<endl; } } printf("Loaded map: %lu vertices, %lu faces\n", m_Faces*3, m_Faces); printf("Map BB: (%.2f -> %.2f, %.2f -> %.2f, %.2f -> %.2f)\n", _minx, _maxx, _miny, _maxy, _minz, _maxz); _3dgraphfile.close(); myfile.close(); return(true); }else{ int ID; float x, y, z, deviation, value; float nodeMinX, nodeMaxX, nodeMinY, nodeMaxY; unsigned long count, offset; unsigned char miscFlag; unsigned short miscNodes[4] = {0}; char buffer[30] = ""; strcpy(fileNamePrefix, "./Maps/Maps/"); strcat(fileNamePrefix, thisZonesName); strcat(fileNamePrefix, fileNameSuffix); mymapfile.open(fileNamePrefix); mapHeader head; mymapfile>>buffer>>count; head.version = count; mymapfile>>buffer>>count; head.face_count = count; mymapfile>>buffer>>count; head.node_count = count; mymapfile>>buffer>>count; head.facelist_count = count; m_Faces = head.face_count; m_Nodes = head.node_count; m_FaceLists = head.facelist_count; mFinalFaces = new FACE [m_Faces]; mNodes = new NODE[m_Nodes]; mFaceLists = new unsigned long[m_FaceLists]; mymapfile>>buffer; mymapfile>>buffer>>value; this->_maxx = value; mymapfile>>buffer>>value; this->_minx = value; mymapfile>>buffer>>value; this->_maxy = value; mymapfile>>buffer>>value; this->_miny = value; mymapfile>>buffer>>value; this->_maxz = value; mymapfile>>buffer>>value; this->_minz = value; mymapfile>>buffer; for(int i = 0; i < m_Faces; i++){ mymapfile>>buffer>>ID; mymapfile>>buffer>>x>>y>>z; mFinalFaces[i].a.x = x; mFinalFaces[i].a.y = y; mFinalFaces[i].a.z = z; mymapfile>>buffer>>x>>y>>z; mFinalFaces[i].b.x = x; mFinalFaces[i].b.y = y; mFinalFaces[i].b.z = z; mymapfile>>buffer>>x>>y>>z; mFinalFaces[i].c.x = x; mFinalFaces[i].c.y = y; mFinalFaces[i].c.z = z; mymapfile>>buffer>>x>>y>>z>>deviation; mFinalFaces[i].nx = x; mFinalFaces[i].ny = y; mFinalFaces[i].nz = z; mFinalFaces[i].nd = deviation; mymapfile>>buffer; } for(int i = 0; i < m_Nodes; i++){ mymapfile>>buffer>>ID; mymapfile>>buffer>>nodeMaxX; mymapfile>>buffer>>nodeMinX; mymapfile>>buffer>>nodeMaxY; mymapfile>>buffer>>nodeMinY; mNodes[i].maxx = nodeMaxX; mNodes[i].minx = nodeMinX; mNodes[i].maxy = nodeMaxY; mNodes[i].miny = nodeMinY; mymapfile>>buffer>>miscFlag; mNodes[i].flags = miscFlag; for(int k = 0; k < 4; k++){ mymapfile>>buffer>>ID; mNodes[i].nodes[k] = ID; } mymapfile>>buffer>>count; mymapfile>>buffer>>offset; mNodes[i].faces.count = count; mNodes[i].faces.offset = offset; mymapfile>>buffer; } for(int i = 0; i < m_FaceLists; i++){ mymapfile>>buffer>>ID; mymapfile>>buffer>>offset; mFaceLists[i] = offset; } return(true); } return(false); }
main(int argc, char* argv[]) { // set up to handle inverse color difference short D709 = 0; short D2020 = 0; short D2020C = 0; float tmpF = 0.0; short HD = 0; // ==1 if 1920x1080 cutout short qHD = 0; // ==1 if 960x540 cutout int frames = -999; short IPixF = 0; short Y500 =0; short Y100 =0; short DXYZ = 1; short BD = 12; // 10 bit mode short Gamma = 10000; short SR=4; unsigned short Half = 2048.0; // e.g half value 12 bits unsigned short Full = 4096.0; // short XX = 0; unsigned short minCV = 0; //12 bits unsigned short maxCV = 4095; short FIR = 1; short FULLRANGE = 0; // default is video range short ALPHA = 0; // no alpha channel is default short numChan2 = 3*2; // only 3 channels rgb with no alpha short numChan = 3; unsigned short D = 4; //D=4 for 12 bits =1 10bits = 16 for 14 bits unsigned short minVR, maxVR, minVRC,maxVRC; // video range is // Luma and R,G,B: CV = Floor(876*D*N+64*D+0.5) // Chroma: CV = Floor(896*D*N+64*D+0.5) //Process Args: short arg = 2; while(arg < argc) { if(strcmp(argv[arg],"-h")==0) { printf("\n ARGS:\n 709 (use Rec709 Color Dif)\n 2020 (use Rec2020 Color Dif)\n HD1920 (Format is 1920x1080 images)\n HD960 (Format is 960x540 images)\n (no args get Y'DzDx color difference and 3840x2160 cutout)\n\n\n"); exit(0); } if(strcmp(argv[arg],"BOX")==0)FIR = 0; if(strcmp(argv[arg],"FULL")==0)FULLRANGE = 1; if(strcmp(argv[arg],"ALPHA")==0){ ALPHA = 1; numChan2= 4*2; numChan = 4; } if(strcmp(argv[arg],"709")==0)D709 = 1; if(strcmp(argv[arg],"2020")==0)D2020 = 1; if(strcmp(argv[arg],"2020C")==0)D2020C = 1; if(strcmp(argv[arg],"HD1920")==0)HD = 1; if(strcmp(argv[arg],"HD960")==0)qHD = 1; if(strcmp(argv[arg],"Y100")==0)Y100 = 1; if(strcmp(argv[arg],"Y500")==0)Y500 = 1; if(strcmp(argv[arg],"B10")==0) { BD = 10; SR=6; Half = 512.0; Full = 1024.0; minCV = 0; maxCV = 1023; D=1; printf("\nprocessing line data 10 bits\n"); } if(strcmp(argv[arg],"B14")==0) { BD = 14; SR=2; Half = 8192; Full = 16384; minCV = 0; maxCV = 16383; D=16; printf("\nprocessing line data 14 bits\n"); } if(strcmp(argv[arg],"G1k")==0){ Gamma = 1; printf("\nUsing Gamma PQ 1k\n"); } if(strcmp(argv[arg],"G10k")==0){ Gamma = 10000; printf("\nUsing Gamma PQ 10k\n"); } if(strcmp(argv[arg],"G1886")==0){ Gamma = 1886; printf("\nUsing Gamma Red1886\n"); } if(D709 || D2020 || D2020C || Y100 || Y500)DXYZ = 0; if(strcmp(argv[arg],"-I")==0){ IPixF = 1; printf("Invalid Pixel printing enabled\n"); } if(strcmp(argv[arg],"-X")==0)XX = 1; if(strcmp(argv[arg],"-f")==0) { arg++; if(arg < argc)frames=atoi(argv[arg]); } arg++; } if(DXYZ)printf("Processing for YDzDx with no comp\n"); if(D709)printf("Processing for Rec709\n"); if(D2020)printf("Processing for Rec2020\n"); if(D2020C)printf("Processing for Rec2020 Constant Luminance\n"); if(DXYZ)printf("Processing for YDzDx\n"); if(Y100)printf("Processing for Y100 comp of YDzDx\n"); if(Y500)printf("Processing for Y500 comp of YDzDx\n"); if(HD)printf("Processing for HD1920x1080\n"); if(qHD)printf("Processing for HD960x540\n"); // Set up for video range if needed if(!FULLRANGE) { printf("Processing for Video Range\n"); minVR = 64*D; maxVR = 876*D+minVR; minVRC = minVR; maxVRC = 896*D+minVRC; //achromatic point for chroma will be "Half"(e.g. 512 for 10 bits, 2048 for 12 bits etc..) } stripsize = 3840*numChan2; stripStart =0; pixelStart = 0; if(HD) { stripsize = 1920*numChan2; numStrips = 1080; } if(qHD) { stripsize= 960*numChan2; numStrips = 540; } printf ("Stripsize (bytes): %d, %d (pixels), numStrips %d \n",stripsize, stripsize/numChan2, numStrips); // Saving Invalid Pixel Data as InvalidPixel.txt: ofstream invPix; if(IPixF) invPix.open("InvalidPixel.txt"); // set up alternate differencing equations for Y'DzwDxw float T,U,V,W; if (Y100) { printf("Setting TUVW for 100nit PQ color difference point\n"); T = 0.98989899; U = 2.0; V = 1.016835017; W = 2.03367; } else if(Y500) { printf("Setting TUVW for 500nit PQ color difference point\n"); T = 0.99203764; U = 2.0; V = 1.013391241; W = 2.026782; } // Readign array (stripsize/numChan2 = 3840 unsigned shorts) unsigned short *yuvLine; // Array to store line of output for writing process // will be allocated to line width with 4 unsigned shorts unsigned short *Line; // Allocate memory to read each image unsigned short** YP; int arraySizeX = stripsize/numChan2 - pixelStart/numChan2; // eg 3840 int arraySizeY = numStrips; int arraySizeXH = arraySizeX/2; // eg 1920 cols int arraySizeYH = arraySizeY/2; // eg 1080 rows printf("Frame Size: %d x %d\n",arraySizeX,arraySizeY); YP = (unsigned short**) malloc(arraySizeX*sizeof(unsigned short*)); // cols for (int i = 0; i < arraySizeX; i++) YP[i] = (unsigned short*) malloc(arraySizeY*sizeof(unsigned short)); //rows // allocate for 444 chroma unsigned short** Cb444; Cb444 = (unsigned short**) malloc(arraySizeX*sizeof(unsigned short*)); // cols for (int i = 0; i < arraySizeX; i++) Cb444[i] = (unsigned short*) malloc(arraySizeY*sizeof(unsigned short)); //rows unsigned short** Cr444; Cr444 = (unsigned short**) malloc(arraySizeX*sizeof(unsigned short*)); // cols for (int i = 0; i < arraySizeX; i++) Cr444[i] = (unsigned short*) malloc(arraySizeY*sizeof(unsigned short)); //rows // allocate for 420 chroma unsigned short** DzP; DzP = (unsigned short**) malloc(arraySizeXH*sizeof(unsigned short*)); // cols for (int i = 0; i < arraySizeXH; i++) DzP[i] = (unsigned short*) malloc(arraySizeYH*sizeof(unsigned short)); // rows unsigned short** DxP; DxP = (unsigned short**) malloc(arraySizeXH*sizeof(unsigned short*)); // cols for (int i = 0; i < arraySizeXH; i++) DxP[i] = (unsigned short*) malloc(arraySizeYH*sizeof(unsigned short)); // rows // set output line array to unsigned short Line = (unsigned short *)malloc(((numChan2/2)*arraySizeX*sizeof(unsigned short))); yuvLine = (unsigned short *) malloc(arraySizeX*sizeof(unsigned short)); // Open yuv file // Open Binary PlanarYUV file for reading: yuvIn.open(argv[1], ios::in | ios::binary); printf("Opened YDzDx.yuv reading...:\n"); // process yuv int tifNum = 0; char tifName[] = "tifXYZ/XpYpZp000000.tif"; // 6 digits int line = 0; int pixel = 0; while(yuvIn) { YnegRMx=0; YnegBMx=0; // read Y' data for ( line = 0;line < arraySizeY;line++) { yuvIn.read((char *)yuvLine, arraySizeX*sizeof(unsigned short)); for ( pixel = 0; pixel < arraySizeX;pixel++) { YP[pixel][line] = yuvLine[pixel]; //printf(" YP[%d][%d]= %d ",pixel,line,YP[pixel][line]); if(!FULLRANGE) { YP[pixel][line] = (YP[pixel][line]<minVR) ? minVR : YP[pixel][line]; YP[pixel][line] = (YP[pixel][line]>maxVR) ? maxVR : YP[pixel][line]; } } } // read Dz data for ( line = 0;line < arraySizeY/2;line++) { yuvIn.read((char *)yuvLine, arraySizeX*sizeof(unsigned short)/2); for ( pixel = 0; pixel < arraySizeX/2;pixel++){ DzP[pixel][line] = yuvLine[pixel]; if(!FULLRANGE) { DzP[pixel][line] = (DzP[pixel][line]<minVRC) ? minVRC : DzP[pixel][line]; DzP[pixel][line] = (DzP[pixel][line]>maxVRC) ? maxVRC : DzP[pixel][line]; } } } // read Dx data for ( line = 0;line < arraySizeY/2;line++) { yuvIn.read((char *)yuvLine, arraySizeX*sizeof(unsigned short)/2); for ( pixel = 0; pixel < arraySizeX/2;pixel++) { DxP[pixel][line] = yuvLine[pixel]; if(!FULLRANGE) { DxP[pixel][line] = (DxP[pixel][line]<minVRC) ? minVRC : DxP[pixel][line]; DxP[pixel][line] = (DxP[pixel][line]>maxVRC) ? maxVRC : DxP[pixel][line]; } } } printf("Writing tifXYZ/XpYpZp%06d.tif\n",tifNum); // Open TIF File sprintf(tifName, "tifXYZ/XpYpZp%06d.tif",tifNum); invalidPixels = 0; tif = TIFFOpen(tifName, "w"); if(ALPHA) { TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 4); } else { TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3); } TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16); TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, arraySizeX); TIFFSetField(tif, TIFFTAG_IMAGELENGTH, arraySizeY); TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 1); TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); if(!FULLRANGE) { // VideoRange Subsample420to444(DzP, Cb444, arraySizeX, arraySizeY, FIR, minVRC, maxVRC); Subsample420to444(DxP, Cr444, arraySizeX, arraySizeY, FIR, minVRC, maxVRC); } else { //Fullrange Subsample420to444(DzP, Cb444, arraySizeX, arraySizeY, FIR, minCV, maxCV); Subsample420to444(DxP, Cr444, arraySizeX, arraySizeY, FIR, minCV, maxCV); } for (int line = 0;line < arraySizeY;line++) { for (unsigned int pixel = 0; pixel < numChan*arraySizeX;pixel+=numChan) { // Y = G = Y // Dz = -0.5*G + 0.5*B = 0.5*Z - 0.5*Y + 2048 // Dx = 0.5*R -0.5*G = 0.5*X - 0.5*Y +2048 // 4095 = 2047.5 * 2 // recall 2047.5 came from adding 2047 to Dz, Dx // and adding 8 during initial round off from 16bits to 12 // Try calculating an average Y to use with subsampled Dz, Dx //Yav = (YP[pixel>>2][line>>1 + line>>1] + YP[1+ pixel>>2][line>>1 + line>>1] + YP[1+pixel>>2][line>>1 + line>>1] + YP[1 + pixel>>2][1 + line>>1 + line>>1])/4; Yav = (int)(YP[pixel/numChan][line]); YavSave = Yav; // keep copy of original Y' // Calculate Ybar if (XX) { short p0 = (pixel/numChan) % 2; short l0 = line % 2; if(p0 == 0 && l0 == 0) { Ybar = (int)(YP[pixel/numChan][line]) + (int)(YP[(pixel+numChan)/numChan][line]) + (int)(YP[pixel/numChan][line+1]) + (int)(YP[(pixel+numChan)/numChan][line+1]); Ybar = Ybar/4; } if(p0 == 1 && l0 == 0) { Ybar = (int)(YP[(pixel-numChan)/numChan][line]) + (int)(YP[pixel/numChan][line]) + (int)(YP[(pixel-numChan)/numChan][line+1]) + (int)(YP[pixel/numChan][line+1]); Ybar = Ybar/4; } if(p0 == 0 && l0 == 1) { Ybar = (int)(YP[pixel/numChan][line-1]) + (int)(YP[(pixel+numChan)/numChan][line-1]) + (int)(YP[pixel/numChan][line]) + (int)(YP[(pixel+numChan)/numChan][line]); Ybar = Ybar/4; } if(p0 == 1 && l0 == 1) { Ybar = (int)(YP[(pixel-numChan)/numChan][line-1]) + (int)(YP[pixel/numChan][line-1]) + (int)(YP[(pixel-numChan)/numChan][line]) + (int)(YP[pixel/numChan][line]); Ybar = Ybar/4; } if(Ybar<1)Ybar = 1; if(Ybar>(Full-1))Ybar=Full-1; } // July 6th 2014 changed from (Half-0.5) to Half-1.0 and // in YDzDx from (Full-1.0) to (Half) done before the multiply by 2 // this mirrors what is in tif2yuv where (Half) is added to chroma after calculation // originally had seen something indicating chroma was to +/- 2047.5 but was never sure // how to do that. Looking at rec2020 where everything is integer // with form like 224*chroma+128 if(DXYZ) { if(XX) { //reconstruct with Ybar then scale float RED,BLUE; RED = (2.0*((float)(Cr444[pixel/numChan][line]) - (float)(Half)) + (float)Ybar) * ((float)Yav)/((float)Ybar); BLUE = (2.0*((float)(Cb444[pixel/numChan][line]) - (float)(Half)) + (float)Ybar) * ((float)Yav)/((float)Ybar); if(RED>(Full-1.5))RED=Full-1.0; if(BLUE>(Full-1.5))BLUE=Full-1.0; Rp = RED; Bp = BLUE; } else { Rp = ((int)2*((int)(Cr444[pixel/numChan][line]) - (int)(Half)) + Yav); Bp = ((int)2*((int)(Cb444[pixel/numChan][line]) - (int)(Half)) + Yav); } } else if (D2020C) { D2020CL((int)(YP[pixel/numChan][line]), Cb444[pixel/numChan][line], Cr444[pixel/numChan][line], Rp, Yav, Bp, FULLRANGE, Gamma, Half, Full); } else if(D2020){ tmpF = ((float)(Cb444[pixel/numChan][line])-(Half))*1.8814 + Yav; if(tmpF > (Full-1.0))tmpF = (Full-1.0); Bp = tmpF; tmpF = ((float)(Cr444[pixel/numChan][line])-(Half))*1.4746 + Yav; if(tmpF > (Full-1.0))tmpF = (Full-1.0); Rp = tmpF; tmpF = ((float)Yav - 0.0593*(float)Bp -0.2627*(float)Rp)/0.6780 +0.5 ; // green if(tmpF > (Full-1.0)) tmpF = (Full-1.0); Yav = tmpF; //green } else if(D709) { tmpF = ((float)(Cb444[pixel/numChan][line])-(Half))*1.8556 + Yav; if(tmpF > (Full-1.0))tmpF = (Full-1.0); Bp = tmpF; tmpF = ((float)(Cr444[pixel/numChan][line])-(Half))*1.5748 + Yav; if(tmpF > (Full-1.0))tmpF = (Full-1.0); Rp = tmpF; tmpF = ((float)Yav - 0.07222*(float)Bp -0.2126*(float)Rp)/0.7152 +0.5 ; // green if(tmpF > (Full-1.0)) tmpF = (Full-1.0); Yav = tmpF; //green } else if(Y100 || Y500) { tmpF = ((float)(Cb444[pixel/numChan][line])-(Half))*W + ((float)Yav)*V; if(tmpF > (Full-1.0))tmpF = (Full-1.0); Bp = tmpF; tmpF = ((float)(Cr444[pixel/numChan][line])-(Half))*U + ((float)Yav)*T; if(tmpF > (Full-1.0))tmpF = (Full-1.0); Rp = tmpF; } else { printf("Can't determine color difference to use?\n\n"); exit(0); } if(Yav < 0) { if(IPixF)invPix << "Pixel=" << pixel/8 << ", " << line << " Y'=" << YavSave << " Dz=" << Cb444[pixel/numChan][line] << " Dx=" << Cr444[pixel/numChan][line] << " G'=" << Yav << " !! Gneg\n"; Yav = 0; invalidPixels++; } if(Rp < 0 ) { //if(IPixF && YavSave>0) if(IPixF && YavSave>0)invPix << "Pixel=" << pixel/8 << ", " << line << " Y'=" << YavSave << " Dz=" << Cb444[pixel/numChan][line] << " Dx=" << Cr444[pixel/numChan][line] << " R'=" << Rp << " !! Rneg\n"; if(Yav > YnegRMx && Yav > 0) { YnegRMx = Yav; printf("Line: %d Pixel: %d, Y %d, Dz: %d, Dx %d, X' %d, YnegRMx %d\n", line,pixel/8, Yav, Cb444[pixel/numChan][line], Cr444[pixel/numChan][line], Rp,YnegRMx); } Rp = 0; // zero invalid pixels whether Yav == 0 or not if(YavSave != 0)invalidPixels++; } if(Bp < 0 ) { //if(IPixF && YavSave>0) if(IPixF && YavSave>0)invPix << "Pixel=" << pixel/8 << ", " << line << " Y'=" << YavSave << " Dz=" << Cb444[pixel/numChan][line] << " Dx=" << Cr444[pixel/numChan][line] << " B'=" << Bp << " !! Bneg\n"; if(Yav > YnegBMx && Yav > 0) { YnegBMx = Yav; printf("Line: %d Pixel: %d, Y %d, Dz: %d, Dx %d, Z' %d,YnegBMx %d\n", line,pixel/8, Yav, Cb444[pixel/numChan][line], Cr444[pixel/numChan][line], Bp, YnegBMx); } Bp = 0; // zero invalid pixels whether Yav == 0 or not if(YavSave != 0)invalidPixels++; } // Insure RGB are clipped to video range if required: if(!FULLRANGE) { Rp = (Rp<minVR) ? minVR : Rp; Yav = (Yav<minVR) ? minVR : Yav; Bp = (Bp<minVR) ? minVR : Bp; Rp = (Rp>maxVR) ? maxVR : Rp; Yav = (Yav>maxVR) ? maxVR : Yav; Bp = (Bp>maxVR) ? maxVR : Bp; } else { Rp = (Rp<minCV) ? minCV : Rp; Yav = (Yav<minCV) ? minCV : Yav; Bp = (Bp<minCV) ? minCV : Bp; Rp = (Rp>maxCV) ? maxCV : Rp; Yav = (Yav>maxCV) ? maxCV : Yav; Bp = (Bp>maxCV) ? maxCV : Bp; } // Calculate Rp from Cr444 // Calculate Bp from Cb444 // R = X = 2*Dx + Y Line[pixel] = ((unsigned short)Rp) << SR; // R = X // G = Y Line[pixel+1] = ((unsigned short)Yav) << SR; //G = Y or inverse 2020/709 equation // B = X = 2*Dx + Y Line[pixel+2] = ((unsigned short)Bp) << SR; // B = Z // A if(ALPHA) Line[pixel+3] = 65535; // A //printf("Rp=%d Gp=%d Bp=%d | ",Line[pixel],Line[pixel+1],Line[pixel+2]); } //printf("Writing strip %d with width %d bytes %d pixels\n",line,4*arraySizeX*2,arraySizeX); TIFFWriteRawStrip(tif, (tstrip_t)line, (tdata_t)Line, numChan2*arraySizeX); } TIFFClose(tif); tifNum++; printf("Max YnegR = %d, Max YnegB = %d\n",YnegRMx, YnegBMx); printf("Invalid Pixels: %d\n",invalidPixels); if(frames > 0) { frames--; if(frames == 0)exit(0); } } if(IPixF) invPix.close(); }