/*! */ void Md_method::run(Program_options & options, ostream & output) { output.precision(10); string logfile=options.runid+".log"; prop.setLog(logfile, log_label); int natoms=sys->nIons(); Array1 < Array1 <int> > atom_move; Array1 < Array2 <doublevar> > displace; //Even numbered displacements are in + direction, odd are in // - direction if(natoms==2) { //For a dimer, assume they are oriented in the z //direction and only move in that direction. atom_move.Resize(4); displace.Resize(4); int count=0; for(int at=0; at < natoms; at++) { for(int s=0; s< 2; s++) { atom_move(count).Resize(1); displace(count).Resize(1,3); atom_move(count)(0)=at; displace(count)=0; if(s==0) displace(count)(0,2)=0.00025; else displace(count)(0,2)=-0.00025; count++; } } } else { int ndim=0; for(int d=0; d< 3; d++) { if(restrict_dimension(d) ==0) ndim++; } atom_move.Resize(2*ndim*natoms); displace.Resize(2*ndim*natoms); int count=0; for(int at=0; at< natoms; at++) { for(int d=0; d< 3; d++) { if(!restrict_dimension(d) ) { for(int s=0; s< 2; s++) { atom_move(count).Resize(1); displace(count).Resize(1,3); atom_move(count)(0)=at; displace(count)=0; if(s==0) displace(count)(0,d)=0.00025; else displace(count)(0,d)=-0.00025; count++; } } } } } prop.setDisplacement(atom_move, displace); Properties_final_average curravg; string vmcout=options.runid+".embed"; ofstream vmcoutput; if(output) vmcoutput.open(vmcout.c_str()); Array3 <doublevar> ionpos(nstep+2, natoms, 3, 0.0); Array1 <doublevar> temppos(3); for(int s=0; s< 2; s++) { for(int at=0; at< natoms; at++) { sys->getIonPos(at, temppos); for(int d=0; d< 3; d++) { ionpos(s,at,d)=temppos(d); } } } if(readcheckfile != "") { read_check(ionpos); } for(int s=0; s< 2; s++) { Array2 <doublevar> pos(ionpos(s)); recenter(pos, atomic_weights); } for(int step=0; step < nstep; step++) { int currt=step+1; //current time for(int at=0; at< natoms; at++) { for(int d=0; d< 3; d++) { temppos(d)=ionpos(currt, at, d); } sys->setIonPos(at, temppos); } qmc_avg->runWithVariables(prop, sys, wfdata, pseudo, vmcoutput); prop.getFinal(curravg); if(output) output << "*****Step " << step << endl; Array2 <doublevar> force(natoms, 3, 0.0); Array2 <doublevar> force_err(natoms, 3, 0.0); for(int f=0; f< atom_move.GetDim(0); f+=2 ) { for(int m=0; m < atom_move(f).GetDim(0); m++) { int at=atom_move(f)(m); for(int d=0; d< 3; d++) { //Take a finite difference between the two forces doublevar prop=fabs(displace(f)(m,d)/curravg.aux_size(f)); doublevar fin_diff=(curravg.aux_diff(f,0)-curravg.aux_diff(f+1,0)) /(2*curravg.aux_size(f)); force(at,d)+= -prop*fin_diff; force_err(at,d)+=prop*(curravg.aux_differr(f,0) +curravg.aux_differr(f+1,0)) /(2*curravg.aux_size(f))/(2*curravg.aux_size(f)); } } } for(int at=0; at< natoms; at++) { for(int d=0; d< 3; d++) force_err(at,d)=sqrt(force_err(at,d)); } //Make sure that Newton's laws are actually followed for //two atoms; we can do this for more, as well. if(natoms==2) { doublevar average=(force(0,2)-force(1,2))/2.0; force(0,2)=average; force(1,2)=-average; } //Verlet algorithm.. for(int at=0; at< natoms; at++) { for(int d=0; d< 3; d++) { ionpos(currt+1, at, d)=ionpos(currt, at,d) +(1-damp)*(ionpos(currt, at, d)-ionpos(currt-1, at,d)) +tstep*tstep*force(at,d)/atomic_weights(at); //cout << "pos " << ionpos(currt, at,d) // << " last " << ionpos(currt-1, at,d) // << " weight " << atomic_weights(at) << endl; } } Array2 <doublevar> currpos(ionpos(currt+1)); recenter(currpos, atomic_weights); doublevar kinen=0; int field=output.precision() + 15; for(int at=0; at < natoms; at++) { if(output) output << "position" << at << " " << setw(field) << ionpos(currt+1, at, 0) << setw(field) << ionpos(currt+1, at, 1) << setw(field) << ionpos(currt+1, at, 2) << endl; Array1 <doublevar> velocity(3); for(int d=0; d< 3; d++) { velocity(d)=(ionpos(currt+1, at, d)-ionpos(currt-1, at,d))/(2*tstep); } for(int d=0;d < 3; d++) { kinen+=.5*atomic_weights(at)*velocity(d)*velocity(d); } if(output ) { output << "velocity" << at << " " << setw(field) << velocity(0) << setw(field) << velocity(1) << setw(field) << velocity(2) << endl; output << "force" << at << " " << setw(field) << force(at,0) << setw(field) << force(at, 1) << setw(field) << force(at,2) << endl; output << "force_err" << at << setw(field) << force_err(at, 0) << setw(field) << force_err(at, 1) << setw(field) << force_err(at, 2) << endl; //output << "force" << at << "z " << force(at,2) << " +/- " // << force_err(at,2) << endl; } } if(output ) { output << "kinetic_energy " << kinen << endl; output << "electronic_energy " << curravg.total_energy(0) << " +/- " << sqrt(curravg.total_energyerr(0)) << endl; output << "total_energy " << curravg.total_energy(0)+kinen << " +/- " << sqrt(curravg.total_energyerr(0)) << endl; if(writecheckfile != "") if(output) write_check(ionpos, currt+1); } } if(output) vmcoutput.close(); }
void Auto::write(ostream& os, Types types) { os.write((char*)&types, sizeof(types)); }
void Auto::write(ostream& os, const char* pStr) { os.write((char*)pStr, strlen(pStr)); }
void DSA1Gen_Entry::write(ostream& strm) { strm.write(name.c_str(), 12); write32(strm, offset); }
void Auto::write(ostream& os, int value) { os.write((char*)&value, sizeof(value)); }
boolean ScrollerCode::ConstDecls(ostream& out) { out << "(const char*, Interactor* i);\n"; return out.good(); }
template<class T> void binwrite(ostream& out, T x) { out.write(reinterpret_cast<char*>(&x), sizeof(T)); }
void derivator_dictionary_encoder::encode(istream& is, istream& dictionary, bool verbose, ostream& os) { // Load the morphology cerr << "Loading morphology: "; auto dictionary_start = dictionary.tellg(); unique_ptr<morpho> morpho(morpho::load(dictionary)); if (!morpho) runtime_failure("Cannot load morpho model from given file!"); if (morpho->get_derivator()) runtime_failure("The given morpho model already has a derivator!"); auto dictionary_end = dictionary.tellg(); cerr << "done" << endl; // Load the derivator cerr << "Loading derivator data: "; struct lemma_info { string sense; string comment; string parent; set<string> parents; unsigned children; unsigned mark; lemma_info(const string& sense = string(), const string& comment = string()) : sense(sense), comment(comment), children(0), mark(0) {} }; map<string, lemma_info> derinet; string line; string part_lid, lemma_lid, lemma_comment; vector<string> tokens; vector<string> parts; unordered_map<string, lemma_info> matched[2]; vector<tagged_lemma_forms> matched_lemmas_forms; while (getline(is, line)) { split(line, '\t', tokens); if (tokens.size() != 2) runtime_failure("Expected two tab separated columns on derivator line '" << line << "'!"); // Generate all possible lemmas and parents for (int i = 0; i < 2; i++) { split(tokens[i], ' ', parts); if (parts.size() > 2) runtime_failure("The derivator lemma desctiption '" << tokens[i] << "' contains two or more spaces!"); bool is_lemma_id = parts.size() == 1; part_lid.assign(parts[0], 0, morpho->lemma_id_len(parts[0])); morpho->generate(parts[0], is_lemma_id ? nullptr : parts[1].c_str(), morpho::NO_GUESSER, matched_lemmas_forms); matched[i].clear(); for (auto&& lemma_forms : matched_lemmas_forms) { lemma_lid.assign(lemma_forms.lemma, 0, morpho->lemma_id_len(lemma_forms.lemma)); if (!is_lemma_id || part_lid == lemma_lid) { // Choose only the shortest lemma comment for the lemma id of lemma_form.lemma lemma_comment.assign(lemma_forms.lemma, lemma_lid.size(), string::npos); auto it = matched[i].emplace(lemma_lid, lemma_info(lemma_lid.substr(morpho->raw_lemma_len(lemma_lid)), lemma_comment)); if (!it.second && (lemma_comment.size() < it.first->second.comment.size() || (lemma_comment.size() == it.first->second.comment.size() && lemma_comment < it.first->second.comment))) it.first->second.comment.assign(lemma_comment); } } } if (matched[0].empty() || matched[1].empty()) { if (verbose) cerr << "Could not match a lemma from line '" << line << "', skipping." << endl; continue; } // Store the possible parents derinet.insert(matched[0].begin(), matched[0].end()); derinet.insert(matched[1].begin(), matched[1].end()); for (auto&& lemma : matched[0]) for (auto&& parent : matched[1]) derinet[lemma.first].parents.insert(parent.first); } cerr << "done" << endl; // Choose unique parent for every lemma for (auto&& lemma : derinet) if (!lemma.second.parents.empty()) { // Try locating lexicographically smallest parent with the same sense for (auto&& parent : lemma.second.parents) if (derinet[parent].sense == lemma.second.sense) { lemma.second.parent.assign(parent); break; } // Otherwise, choose the lexicographically smallest parent if (lemma.second.parent.empty()) lemma.second.parent.assign(*lemma.second.parents.begin()); // Add this edge also to the parent derinet[lemma.second.parent].children++; if (verbose) cerr << lemma.first << lemma.second.comment << " -> " << lemma.second.parent << derinet[lemma.second.parent].comment << endl; } // Make sure the derinet contains no cycles unsigned mark = 0; for (auto&& lemma : derinet) { lemma.second.mark = ++mark; for (auto node = derinet.find(lemma.first); !node->second.parent.empty(); ) { node = derinet.find(node->second.parent); if (node->second.mark) { if (node->second.mark == mark) runtime_failure("The derivator data contains a cycle with lemma '" << lemma.first << "'!"); break; } node->second.mark = mark; } } // Encode the derivator cerr << "Encoding derivator: "; os.put(morpho_ids::DERIVATOR_DICTIONARY); binary_encoder enc; vector<int> lengths; for (auto&& lemma : derinet) { if (lemma.first.size() >= lengths.size()) lengths.resize(lemma.first.size() + 1); lengths[lemma.first.size()]++; } enc.add_1B(lengths.size()); for (auto&& length : lengths) enc.add_4B(length); enc.add_4B(derinet.size()); string prev = ""; for (auto&& lemma : derinet) { int cpl = 0; while (prev[cpl] && prev[cpl] == lemma.first[cpl]) cpl++; enc.add_1B(prev.size() - cpl); enc.add_1B(lemma.first.size() - cpl); enc.add_data(lemma.first.c_str() + cpl); enc.add_1B(lemma.second.comment.size()); enc.add_data(lemma.second.comment); enc.add_2B(lemma.second.children); if (lemma.second.parent.empty()) { enc.add_1B(0); } else { unsigned best_lemma_from = 0, best_parent_from = 0, best_len = 0; for (unsigned lemma_from = 0; lemma_from < lemma.first.size(); lemma_from++) for (unsigned parent_from = 0; parent_from < lemma.second.parent.size(); parent_from++) { unsigned len = 0; while (lemma_from + len < lemma.first.size() && parent_from + len < lemma.second.parent.size() && lemma.first[lemma_from+len] == lemma.second.parent[parent_from+len]) len++; if (len > best_len) best_lemma_from = lemma_from, best_parent_from = parent_from, best_len = len; } enum { REMOVE_START = 1, REMOVE_END = 2, ADD_START = 4, ADD_END = 8 }; enc.add_1B(REMOVE_START * (best_lemma_from>0) + REMOVE_END * (best_lemma_from+best_len<lemma.first.size()) + ADD_START * (best_parent_from>0) + ADD_END * (best_parent_from+best_len<lemma.second.parent.size())); if (best_lemma_from > 0) enc.add_1B(best_lemma_from); if (best_lemma_from + best_len < lemma.first.size()) enc.add_1B(lemma.first.size() - best_lemma_from - best_len); if (best_parent_from > 0) { enc.add_1B(best_parent_from); enc.add_data(string_piece(lemma.second.parent.c_str(), best_parent_from)); } if (best_parent_from + best_len < lemma.second.parent.size()) { enc.add_1B(lemma.second.parent.size() - best_parent_from - best_len); enc.add_data(lemma.second.parent.c_str() + best_parent_from + best_len); } } prev.assign(lemma.first); } compressor::save(os, enc); // Append the morphology after the derivator dictionary model if (!dictionary.seekg(dictionary_start, dictionary.beg)) runtime_failure("Cannot seek in the morpho model!"); for (auto length = dictionary_end - dictionary_start; length; length--) os.put(dictionary.get()); cerr << "done" << endl; }
inline void __SaveString(const string &s, ostream &out) { size_t len= s.size(); out.write((char*)&len, sizeof(len)); out.write(s.c_str(), len*sizeof(char)); }
//*************************************************************************** // PUBLIC METHOD: // void ossimFfRevb::write(ostream& os) const // // Writes an EOSAT Fast Format Rev B formatted header. //*************************************************************************** void ossimFfRevb::write(ostream& os) const { const char PRODUCT_ID_DESC [PRODUCT_ORDER_NUMBER_DESC_SIZE + 1] = "PRODUCT ="; const char WRS_DESC [WRS_DESC_SIZE + 1] = " WRS ="; const char DATE_DESC [DATE_DESC_SIZE + 1] = " ACQUISITION DATE ="; const char SATELLITE_NUMBER_DESC [SAT_NUMBER_DESC_SIZE + 1] = " SATELLITE ="; const char INSTRUMENT_TYPE_DESC [INSTRUMENT_TYPE_DESC_SIZE + 1] = " INSTRUMENT ="; const char PRODUCT_TYPE_DESC [PRODUCT_TYPE_DESC_SIZE + 1] = " PRODUCT TYPE ="; const char PRODUCT_SIZE_DESC [PRODUCT_SIZE_DESC_SIZE + 1] = " PRODUCT SIZE ="; const char PROCESSING_TYPE_DESC [PROCESSING_TYPE_DESC_SIZE + 1] = " TYPE OF GEODETIC PROCESSING ="; const char RESAMPLING_ALGO_DESC [RESAMPLING_ALGO_DESC_SIZE + 1] = " RESAMPLING ="; const char RADIANCE_DESC [RADIANCE_DESC_SIZE + 1] = " RAD GAINS/BIASES = "; const char VOLUME_NUMBER_DESC [VOLUME_NUMBER_DESC_SIZE + 1] = " TAPE SPANNING FLAG="; const char FIRST_LINE_DESC [FIRST_LINE_DESC_SIZE + 1] = " START LINE #="; const char LINES_PER_VOLUME_DESC [LINES_PER_VOLUME_DESC_SIZE + 1] = " LINES PER VOL="; const char ORIENTATION_ANGLE_DESC [ORIENTATION_ANGLE_DESC_SIZE + 1] = " ORIENTATION ="; const char MAP_PROJ_NAME_DESC [MAP_PROJ_NAME_DESC_SIZE + 1] = " PROJECTION ="; const char USGS_PROJ_NUMBER_DESC [USGS_PROJ_NUMBER_DESC_SIZE + 1] = " USGS PROJECTION # ="; const char USGS_MAP_ZONE_DESC [USGS_MAP_ZONE_DESC_SIZE + 1] = " USGS MAP ZONE ="; const char PROJECTION_PARAMETER_DESC [USGS_PROJ_PARAMS_DESC_SIZE + 1] = " USGS PROJECTION PARAMETERS ="; const char ELLIPSOID_DESC [ELLIPSOID_DESC_SIZE + 1] = " EARTH ELLIPSOID ="; const char MAJOR_AXIS_DESC [MAJOR_AXIS_DESC_SIZE+ 1] = " SEMI-MAJOR AXIS ="; const char MINOR_AXIS_DESC [MINOR_AXIS_DESC_SIZE+ 1] = " SEMI-MINOR AXIS ="; const char PIXEL_GSD_DESC [PIXEL_GSD_DESC_SIZE + 1] = " PIXEL SIZE ="; const char PIXELS_PER_LINE_DESC [PIXELS_PER_LINE_DESC_SIZE + 1] = " PIXELS PER LINE="; const char LINES_PER_IMAGE_DESC [LINES_PER_IMAGE_DESC_SIZE + 1] = " LINES PER IMAGE="; const char UL_DESC [CORNER_DESC_SIZE + 1] = " UL "; const char UR_DESC [CORNER_DESC_SIZE + 1] = " UR "; const char LR_DESC [CORNER_DESC_SIZE + 1] = " LR "; const char LL_DESC [CORNER_DESC_SIZE + 1] = " LL "; const char BANDS_PRESENT_DESC [BANDS_PRESENT_DESC_SIZE + 1] = " BANDS PRESENT ="; const char BLOCKING_FACTOR_DESC [BLOCKING_FACTOR_DESC_SIZE + 1] = " BLOCKING FACTOR ="; const char RECORD_LENGTH_DESC [RECORD_LENGTH_DESC_SIZE + 1] = " RECORD LENGTH ="; const char SUN_ELEVATION_DESC [SUN_ELEVATION_DESC_SIZE + 1] = " SUN ELEVATION ="; const char SUN_AZIMUTH_DESC [SUN_AZIMUTH_DESC_SIZE + 1] = " SUN AZIMUTH ="; const char CENTER_DESC [CENTER_DESC_SIZE + 1] = " CENTER "; const char OFFSET_DESC [OFFSET_DESC_SIZE + 1] = " OFFSET="; const char REV_DESC [REV_DESC_SIZE + 1] = " REV"; const char SPACE[] = " "; //*** // Start at beginning of the stream. //*** os.seekp(0, ios::beg); os << setiosflags(ios::fixed) // Disable scientific mode. << setiosflags(ios::left) << PRODUCT_ID_DESC << setw(PRODUCT_ORDER_NUMBER_SIZE) << theProductOrderNumber << WRS_DESC << setw(PATH_ROW_NUMBER_SIZE) << thePathRowNumber << DATE_DESC << setw(DATE_SIZE) << theAcquisitionDate << SATELLITE_NUMBER_DESC << setw(SAT_NUMBER_SIZE) << theSatNumber << INSTRUMENT_TYPE_DESC << setw(INSTRUMENT_TYPE_SIZE) << theInstrumentType << PRODUCT_TYPE_DESC << setw(PRODUCT_TYPE_SIZE) << theProductType << PRODUCT_SIZE_DESC << setw(PRODUCT_SIZE_SIZE) << theProductSize << setw(MAP_SHEET_SIZE) << theMapSheetName << PROCESSING_TYPE_DESC << setw(PROCESSING_TYPE_SIZE) << theProcessingType << RESAMPLING_ALGO_DESC << setw(RESAMPLING_ALGO_SIZE) << theResampAlgorithm << RADIANCE_DESC; int i; for (i=0; i<NUMBER_OF_BANDS-1; i++) // Output six of the seven bands. { os << setw(RADIANCE_SIZE) << theBandRadiance[i] << SPACE; } os << setw(RADIANCE_SIZE) << theBandRadiance[6] // Last one no space. << VOLUME_NUMBER_DESC << setw(VOLUME_NUMBER_SIZE) << theVolumeNumber << resetiosflags(ios::left) << setiosflags(ios::right) << FIRST_LINE_DESC << setw(FIRST_LINE_IN_VOLUME_SIZE) << the1stLineInVolume << LINES_PER_VOLUME_DESC << setw(LINES_PER_VOLUME_SIZE) << theLinesPerVolume << ORIENTATION_ANGLE_DESC << setprecision(2) << setw(ORIENTATION_ANGLE_SIZE) << theOrientationAngle << MAP_PROJ_NAME_DESC << setw(MAP_PROJ_NAME_SIZE) << theMapProjName << USGS_PROJ_NUMBER_DESC << setw(USGS_PROJ_NUMBER_SIZE) << theUsgsProjNumber << USGS_MAP_ZONE_DESC << setw(USGS_MAP_ZONE_SIZE) << theUsgsMapZone << PROJECTION_PARAMETER_DESC; for (i=0; i<NUMBER_OF_PROJECTION_PARAMETERS; i++) { os << setw(USGS_PROJ_PARAMS_SIZE) << theUsgsProjParam[i]; } os << setiosflags(ios::left) << ELLIPSOID_DESC << setw(ELLIPSOID_SIZE) << theEllipsoid << resetiosflags(ios::left) << setprecision(3) << setiosflags(ios::right) << MAJOR_AXIS_DESC << setw(MAJOR_AXIS_SIZE) << theSemiMajorAxis << MINOR_AXIS_DESC << setw(MINOR_AXIS_SIZE) << theSemiMinorAxis << setprecision(2) << PIXEL_GSD_DESC << setw(PIXEL_GSD_SIZE) << theGsd << PIXELS_PER_LINE_DESC << setw(PIXELS_PER_LINE_SIZE) << thePixelsPerLine << LINES_PER_IMAGE_DESC << setw(LINES_PER_IMAGE_SIZE) << theLinesPerImage << setprecision(3) << UL_DESC << setw(LON_SIZE) << theUlLon << SPACE << setw(LAT_SIZE) << theUlLat << SPACE << setw(EASTING_SIZE) << theUlEasting << SPACE << setw(NORTHING_SIZE) << theUlNorthing << UR_DESC << setw(LON_SIZE) << theUrLon << SPACE << setw(LAT_SIZE) << theUrLat << SPACE << setw(EASTING_SIZE) << theUrEasting << SPACE << setw(NORTHING_SIZE) << theUrNorthing << LR_DESC << setw(LON_SIZE) << theLrLon << SPACE << setw(LAT_SIZE) << theLrLat << SPACE << setw(EASTING_SIZE) << theLrEasting << SPACE << setw(NORTHING_SIZE) << theLrNorthing << LL_DESC << setw(LON_SIZE) << theLlLon << SPACE << setw(LAT_SIZE) << theLlLat << SPACE << setw(EASTING_SIZE) << theLlEasting << SPACE << setw(NORTHING_SIZE) << theLlNorthing << resetiosflags(ios::right); os << BANDS_PRESENT_DESC << setw(BANDS_PRESENT_SIZE) << theBandsPresentString << BLOCKING_FACTOR_DESC << setw(BLOCKING_FACTOR_SIZE) << theBlockingFactor << RECORD_LENGTH_DESC << setw(RECORD_LENGTH_SIZE) << theRecordSize << SUN_ELEVATION_DESC << setw(SUN_ELEVATION_SIZE) << theSunElevation << SUN_AZIMUTH_DESC << setw(SUN_AZIMUTH_SIZE) << theSunAzimuth << CENTER_DESC << setw(LON_SIZE) << theCenterLon << SPACE << setw(LAT_SIZE) << theCenterLat << SPACE << setiosflags(ios::right) << setw(EASTING_SIZE) << theCenterEasting << SPACE << setw(NORTHING_SIZE) << theCenterNorthing << setw(CENTER_SAMPLE_SIZE) << theCenterSample << setw(CENTER_LINE_SIZE) << theCenterLine << OFFSET_DESC << setw(OFFSET_SIZE) << theOffset << REV_DESC << setw(FORMAT_VERSION_SIZE) << theFormatVersion << flush; // Byte count of file should be 1536. }
namespace utils { // Repository of all categories and commands const MetaCategory* MetaCategory::firstCategory = nullptr; MetaCategory::CategoryMap MetaCategory::categoriesByTag; MetaCategory::CategoryMap MetaCategory::categoriesByGroupTag; const MetaCategory* Object::metadata = nullptr; // Generic Python type for timeline events PythonType* EventPythonType = nullptr; // Repository of loaded modules set<string> Environment::moduleRegistry; // Number of processors. // The value initialized here is updated when the getProcessorCores function // is called the first time. int Environment::processorcores = -1; // Output logging stream, whose input buffer is shared with either // Environment::logfile or cout. ostream logger(cout.rdbuf()); // Output file stream ofstream Environment::logfile; // Name of the log file string Environment::logfilename; // Hash value computed only once const hashtype MetaCategory::defaultHash(Keyword::hash("default")); vector<PythonType*> Object::table; void LibraryUtils::initialize() { // Initialize only once static bool init = false; if (init) { logger << "Warning: Calling frepple::LibraryUtils::initialize() more " << "than once." << endl; return; } init = true; // Initialize Xerces parser xercesc::XMLPlatformUtils::Initialize(); // Initialize the Python interpreter PythonInterpreter::initialize(); // Register new methods in Python PythonInterpreter::registerGlobalMethod( "loadmodule", loadModule, METH_VARARGS, "Dynamically load a module in memory."); } string Environment::searchFile(const string filename) { #ifdef _MSC_VER static char pathseperator = '\\'; #else static char pathseperator = '/'; #endif // First: check the current directory struct stat stat_p; int result = stat(filename.c_str(), &stat_p); if (!result && (stat_p.st_mode & S_IREAD)) return filename; // Second: check the FREPPLE_HOME directory, if it is defined string fullname; char * envvar = getenv("FREPPLE_HOME"); if (envvar) { fullname = envvar; if (*fullname.rbegin() != pathseperator) fullname += pathseperator; fullname += filename; result = stat(fullname.c_str(), &stat_p); if (!result && (stat_p.st_mode & S_IREAD)) return fullname; } #ifdef DATADIRECTORY // Third: check the data directory fullname = DATADIRECTORY; if (*fullname.rbegin() != pathseperator) fullname += pathseperator; fullname.append(filename); result = stat(fullname.c_str(), &stat_p); if (!result && (stat_p.st_mode & S_IREAD)) return fullname; #endif #ifdef LIBDIRECTORY // Fourth: check the lib directory fullname = LIBDIRECTORY; if (*fullname.rbegin() != pathseperator) fullname += pathseperator; fullname += "frepple"; fullname += pathseperator; fullname += filename; result = stat(fullname.c_str(), &stat_p); if (!result && (stat_p.st_mode & S_IREAD)) return fullname; #endif #ifdef SYSCONFDIRECTORY // Fifth: check the sysconf directory fullname = SYSCONFDIRECTORY; if (*fullname.rbegin() != pathseperator) fullname += pathseperator; fullname += filename; result = stat(fullname.c_str(), &stat_p); if (!result && (stat_p.st_mode & S_IREAD)) return fullname; #endif // Not found return ""; } int Environment::getProcessorCores() { // Previously detected already if (processorcores >= 1) return processorcores; // Detect the number of cores on the machine #ifdef WIN32 // Windows SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); processorcores = sysinfo.dwNumberOfProcessors; #else // Linux, Solaris and AIX. // Tough luck for other platforms. processorcores = sysconf(_SC_NPROCESSORS_ONLN); #endif // Detection failed... if (processorcores<1) processorcores = 1; return processorcores; } void Environment::setLogFile(const string& x) { // Bye bye message if (!logfilename.empty()) logger << "Stop logging at " << Date::now() << endl; // Close an eventual existing log file. if (logfile.is_open()) logfile.close(); // No new logfile specified: redirect to the standard output stream if (x.empty() || x == "+") { logfilename = x; logger.rdbuf(cout.rdbuf()); return; } // Open the file: either as a new file, either appending to existing file if (x[0] != '+') logfile.open(x.c_str(), ios::out); else logfile.open(x.c_str()+1, ios::app); if (!logfile.good()) { // Redirect to the previous logfile (or cout if that's not possible) if (logfile.is_open()) logfile.close(); logfile.open(logfilename.c_str(), ios::app); logger.rdbuf(logfile.is_open() ? logfile.rdbuf() : cout.rdbuf()); // The log file could not be opened throw RuntimeException("Could not open log file '" + x + "'"); } // Store the file name logfilename = x; // Redirect the log file. logger.rdbuf(logfile.rdbuf()); // Print a nice header logger << "Start logging frePPLe " << PACKAGE_VERSION << " (" << __DATE__ << ") at " << Date::now() << endl; } void Environment::loadModule(string lib) { // Type definition of the initialization function typedef const char* (*func)(); // Validate if (lib.empty()) throw DataException("Error: No library name specified for loading"); #ifdef WIN32 // Load the library - The windows way // Change the error mode: we handle errors now, not the operating system UINT em = SetErrorMode(SEM_FAILCRITICALERRORS); HINSTANCE handle = LoadLibraryEx(lib.c_str(),nullptr,LOAD_WITH_ALTERED_SEARCH_PATH); if (!handle) handle = LoadLibraryEx(lib.c_str(), nullptr, 0); if (!handle) { // Get the error description char error[256]; FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, GetLastError(), 0, error, 256, nullptr ); throw RuntimeException(error); } SetErrorMode(em); // Restore the previous error mode // Find the initialization routine func inithandle = reinterpret_cast<func>(GetProcAddress(HMODULE(handle), "initialize")); if (!inithandle) { // Get the error description char error[256]; FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, GetLastError(), 0, error, 256, nullptr ); throw RuntimeException(error); } #else // Load the library - The UNIX way // Search the frePPLe directories for the library string fullpath = Environment::searchFile(lib); if (fullpath.empty()) throw RuntimeException("Module '" + lib + "' not found"); dlerror(); // Clear the previous error void *handle = dlopen(fullpath.c_str(), RTLD_NOW | RTLD_GLOBAL); const char *err = dlerror(); // Pick up the error string if (err) { // Search the normal path for the library dlerror(); // Clear the previous error handle = dlopen(lib.c_str(), RTLD_NOW | RTLD_GLOBAL); err = dlerror(); // Pick up the error string if (err) throw RuntimeException(err); } // Find the initialization routine func inithandle = (func)(dlsym(handle, "initialize")); err = dlerror(); // Pick up the error string if (err) throw RuntimeException(err); #endif // Call the initialization routine with the parameter list string x = (inithandle)(); if (x.empty()) throw DataException("Invalid module"); // Insert the new module in the registry moduleRegistry.insert(x); } void MetaClass::addClass (const string& a, const string& b, bool def, creatorDefault f) { // Find or create the category MetaCategory* cat = const_cast<MetaCategory*>(MetaCategory::findCategoryByTag(a.c_str())); // Check for a valid category if (!cat) throw LogicException("Category " + a + " not found when registering class " + b); // Update fields type = b.empty() ? "unspecified" : b; typetag = &Keyword::find(type.c_str()); category = cat; // Update the metadata table cat->classes[Keyword::hash(b)] = this; // Register this tag also as the default one, if requested if (isDefault) cat->classes[Keyword::hash("default")] = this; // Set method pointers to nullptr factoryMethod = f; } MetaCategory::MetaCategory (const string& a, const string& gr, size_t sz, readController f, findController s) { // Update registry if (!a.empty()) categoriesByTag[Keyword::hash(a)] = this; if (!gr.empty()) categoriesByGroupTag[Keyword::hash(gr)] = this; // Update fields size = sz; readFunction = f; findFunction = s; type = a.empty() ? "unspecified" : a; typetag = &Keyword::find(type.c_str()); group = gr.empty() ? "unspecified" : gr; grouptag = &Keyword::find(group.c_str()); // Maintain a linked list of all registered categories nextCategory = nullptr; if (!firstCategory) firstCategory = this; else { const MetaCategory *i = firstCategory; while (i->nextCategory) i = i->nextCategory; const_cast<MetaCategory*>(i)->nextCategory = this; } } const MetaCategory* MetaCategory::findCategoryByTag(const char* c) { // Loop through all categories CategoryMap::const_iterator i = categoriesByTag.find(Keyword::hash(c)); return (i!=categoriesByTag.end()) ? i->second : nullptr; } const MetaCategory* MetaCategory::findCategoryByTag(const hashtype h) { // Loop through all categories CategoryMap::const_iterator i = categoriesByTag.find(h); return (i!=categoriesByTag.end()) ? i->second : nullptr; } const MetaCategory* MetaCategory::findCategoryByGroupTag(const char* c) { // Loop through all categories CategoryMap::const_iterator i = categoriesByGroupTag.find(Keyword::hash(c)); return (i!=categoriesByGroupTag.end()) ? i->second : nullptr; } const MetaCategory* MetaCategory::findCategoryByGroupTag(const hashtype h) { // Loop through all categories CategoryMap::const_iterator i = categoriesByGroupTag.find(h); return (i!=categoriesByGroupTag.end()) ? i->second : nullptr; } const MetaClass* MetaCategory::findClass(const char* c) const { // Look up in the registered classes MetaCategory::ClassMap::const_iterator j = classes.find(Keyword::hash(c)); return (j == classes.end()) ? nullptr : j->second; } const MetaClass* MetaCategory::findClass(const hashtype h) const { // Look up in the registered classes MetaCategory::ClassMap::const_iterator j = classes.find(h); return (j == classes.end()) ? nullptr : j->second; } const MetaClass* MetaClass::findClass(const char* c) { // Loop through all categories for (MetaCategory::CategoryMap::const_iterator i = MetaCategory::categoriesByTag.begin(); i != MetaCategory::categoriesByTag.end(); ++i) { // Look up in the registered classes MetaCategory::ClassMap::const_iterator j = i->second->classes.find(Keyword::hash(c)); if (j != i->second->classes.end()) return j->second; } // Not found... return nullptr; } void MetaClass::printClasses() { logger << "Registered classes:" << endl; // Loop through all categories for (MetaCategory::CategoryMap::const_iterator i = MetaCategory::categoriesByTag.begin(); i != MetaCategory::categoriesByTag.end(); ++i) { logger << " " << i->second->type << endl; // Loop through the classes for the category for (MetaCategory::ClassMap::const_iterator j = i->second->classes.begin(); j != i->second->classes.end(); ++j) if (j->first == Keyword::hash("default")) logger << " default ( = " << j->second->type << " )" << j->second << endl; else logger << " " << j->second->type << j->second << endl; } } const MetaFieldBase* MetaClass::findField(const Keyword& key) const { for (fieldlist::const_iterator i = fields.begin(); i != fields.end(); ++i) if ((*i)->getName() == key) return *i; return nullptr; } const MetaFieldBase* MetaClass::findField(hashtype h) const { for (fieldlist::const_iterator i = fields.begin(); i != fields.end(); ++i) if ((*i)->getHash() == h) return *i; return nullptr; } Action MetaClass::decodeAction(const char *x) { // Validate the action if (!x) throw LogicException("Invalid action nullptr"); else if (!strcmp(x, "AC")) return ADD_CHANGE; else if (!strcmp(x, "A")) return ADD; else if (!strcmp(x, "C")) return CHANGE; else if (!strcmp(x, "R")) return REMOVE; else throw DataException("Invalid action '" + string(x) + "'"); } Action MetaClass::decodeAction(const DataValueDict& atts) { // Decode the string and return the default in the absence of the attribute const DataValue* c = atts.get(Tags::action); return c ? decodeAction(c->getString().c_str()) : ADD_CHANGE; } bool MetaClass::raiseEvent(Object* v, Signal a) const { bool result(true); for (list<Functor*>::const_iterator i = subscribers[a].begin(); i != subscribers[a].end(); ++i) // Note that we always call all subscribers, even if one or more // already replied negatively. However, an exception thrown from a // callback method will break the publishing chain. if (!(*i)->callback(v,a)) result = false; // Raise the event also on the category, if there is a valid one return (category && category!=this) ? (result && category->raiseEvent(v,a)) : result; } Object* MetaCategory::ControllerDefault ( const MetaClass* cat, const DataValueDict& in, CommandManager* mgr ) { Action act = MetaClass::decodeAction(in); switch (act) { case REMOVE: throw DataException ("Entity " + cat->type + " doesn't support REMOVE action"); case CHANGE: throw DataException ("Entity " + cat->type + " doesn't support CHANGE action"); default: /* Lookup the class in the map of registered classes. */ const MetaClass* j; if (cat->category) // Class metadata passed: we already know what type to create j = cat; else { // Category metadata passed: we need to look up the type const DataValue* type = in.get(Tags::type); j = static_cast<const MetaCategory&>(*cat).findClass( type ? Keyword::hash(type->getString()) : MetaCategory::defaultHash ); if (!j) { string t(type ? type->getString() : "default"); throw LogicException("No type " + t + " registered for category " + cat->type); } } // Call the factory method assert(j->factoryMethod); Object* result = j->factoryMethod(); // Run the callback methods if (!result->getType().raiseEvent(result, SIG_ADD)) { // Creation denied delete result; throw DataException("Can't create object"); } // Report the creation to the manager if (mgr) mgr->add(new CommandCreateObject(result)); // Creation accepted return result; } throw LogicException("Unreachable code reached"); return nullptr; } bool matchWildcard(const char* wild, const char *str) { // Empty arguments: always return a match if (!wild || !str) return 1; const char *cp = nullptr, *mp = nullptr; while ((*str) && *wild != '*') { if (*wild != *str && *wild != '?') // Does not match return 0; wild++; str++; } while (*str) { if (*wild == '*') { if (!*++wild) return 1; mp = wild; cp = str+1; } else if (*wild == *str || *wild == '?') { wild++; str++; } else { wild = mp; str = cp++; } } while (*wild == '*') wild++; return !*wild; } } // end namespace
IndentedStream::IndentedStreamBuffer::IndentedStreamBuffer (ostream& os, const string& indent): os(os), indent(indent) { os.write(indent.data(), indent.size()); }
void RandomDrop::Save(ostream& File)const { File.write(Id,4u); File.write((char*)&Chance,4u); }
//============================================================================== void Epetra_BlockMap::Print(ostream & os) const { int * FirstPointInElementList1 = 0; int * ElementSizeList1 = 0; if (!ConstantElementSize()) { FirstPointInElementList1 = FirstPointInElementList(); ElementSizeList1 = ElementSizeList(); } int MyPID = Comm().MyPID(); int NumProc = Comm().NumProc(); for (int iproc = 0; iproc < NumProc; iproc++) { if (MyPID == iproc) { if (MyPID == 0) { os << "\nNumber of Global Elements = "; os << NumGlobalElements64(); os << endl; os << "Number of Global Points = "; os << NumGlobalPoints64(); os << endl; os << "Maximum of all GIDs = "; os << MaxAllGID64(); os << endl; os << "Minimum of all GIDs = "; os << MinAllGID64(); os << endl; os << "Index Base = "; os << IndexBase(); os << endl; if (ConstantElementSize()) os << "Constant Element Size = "; os << ElementSize(); os << endl; } os << endl; os << "Number of Local Elements = "; os << NumMyElements(); os << endl; os << "Number of Local Points = "; os << NumMyPoints(); os << endl; os << "Maximum of my GIDs = "; os << MaxMyGID64(); os << endl; os << "Minimum of my GIDs = "; os << MinMyGID64(); os << endl; os << endl; os.width(14); os << " MyPID"; os << " "; os.width(14); os << " Local Index "; os << " "; os.width(14); os << " Global Index "; os << " "; if (!ConstantElementSize()) { os.width(14); os <<" FirstPointInElement "; os << " "; os.width(14); os <<" ElementSize "; os << " "; } os << endl; for (int i = 0; i < NumMyElements(); i++) { os.width(14); os << MyPID; os << " "; os.width(14); os << i; os << " "; os.width(14); if(BlockMapData_->GlobalIndicesLongLong_) { #ifndef EPETRA_NO_64BIT_GLOBAL_INDICES long long * MyGlobalElements1 = MyGlobalElements64(); os << MyGlobalElements1[i]; os << " "; #else throw ReportError("Epetra_BlockMap::Print: ERROR, GlobalIndicesLongLong but no API for it.",-1); #endif } else if(BlockMapData_->GlobalIndicesInt_) { #ifndef EPETRA_NO_32BIT_GLOBAL_INDICES int * MyGlobalElements1 = MyGlobalElements(); os << MyGlobalElements1[i]; os << " "; #else throw ReportError("Epetra_BlockMap::Print: ERROR, no GlobalIndicesLongLong but no API for it.",-1); #endif } if (!ConstantElementSize()) { os.width(14); os << FirstPointInElementList1[i]; os << " "; os.width(14); os << ElementSizeList1[i]; os << " "; } os << endl; } os << flush; } // Do a few global ops to give I/O a chance to complete Comm().Barrier(); Comm().Barrier(); Comm().Barrier(); } return; }
ExitCodes outputTo(ostream& os) { //------------------------------------------------------------- // Parameter handling //------------------------------------------------------------- // File names String in = getStringOption_("in"); // File type FileHandler fh; FileTypes::Type in_type = FileTypes::nameToType(getStringOption_("in_type")); if (in_type == FileTypes::UNKNOWN) { in_type = fh.getType(in); writeDebug_(String("Input file type: ") + FileTypes::typeToName(in_type), 2); } if (in_type == FileTypes::UNKNOWN) { writeLog_("Error: Could not determine input file type!"); return PARSE_ERROR; } MSExperiment<Peak1D> exp; FeatureMap feat; ConsensusMap cons; if (in_type == FileTypes::FEATUREXML) //features { FeatureXMLFile().load(in, feat); feat.updateRanges(); } else if (in_type == FileTypes::CONSENSUSXML) //consensus features { ConsensusXMLFile().load(in, cons); cons.updateRanges(); } //------------------------------------------------------------- // meta information //------------------------------------------------------------- if (getFlag_("m")) { os << endl << "-- General information --" << endl << endl << "file name: " << in << endl << "file type: " << FileTypes::typeToName(in_type) << endl; //basic info os << endl << "-- Meta information --" << endl << endl; if (in_type == FileTypes::FEATUREXML) //features { os << "Document id : " << feat.getIdentifier() << endl << endl; } else if (in_type == FileTypes::CONSENSUSXML) //consensus features { os << "Document id : " << cons.getIdentifier() << endl << endl; } } //------------------------------------------------------------- // data processing //------------------------------------------------------------- if (getFlag_("p")) { //basic info os << endl << "-- Data processing information --" << endl << endl; //get data processing info vector<DataProcessing> dp; if (in_type == FileTypes::FEATUREXML) //features { dp = feat.getDataProcessing(); } else if (in_type == FileTypes::CONSENSUSXML) //consensus features { dp = cons.getDataProcessing(); } int i = 0; for (vector<DataProcessing>::iterator it = dp.begin(); it != dp.end(); ++it) { os << "Data processing " << i << endl; os << "\tcompletion_time: " << (*it).getCompletionTime().getDate() << 'T' << (*it).getCompletionTime().getTime() << endl; os << "\tsoftware name: " << (*it).getSoftware().getName() << " version " << (*it).getSoftware().getVersion() << endl; for (set<DataProcessing::ProcessingAction>::const_iterator paIt = (*it).getProcessingActions().begin(); paIt != (*it).getProcessingActions().end(); ++paIt) { os << "\t\tprocessing action: " << DataProcessing::NamesOfProcessingAction[*paIt] << endl; } } ++i; } //------------------------------------------------------------- // statistics //------------------------------------------------------------- if (getFlag_("s")) { //------------------------------------------------------------- // Content statistics //------------------------------------------------------------- Map<String, int> meta_names; if (in_type == FileTypes::FEATUREXML) //features { os << "Number of features: " << feat.size() << endl << endl << "Ranges:" << endl << " retention time: " << String::number(feat.getMin()[Peak2D::RT], 2) << " : " << String::number(feat.getMax()[Peak2D::RT], 2) << endl << " mass-to-charge: " << String::number(feat.getMin()[Peak2D::MZ], 2) << " : " << String::number(feat.getMax()[Peak2D::MZ], 2) << endl << " intensity: " << String::number(feat.getMinInt(), 2) << " : " << String::number(feat.getMaxInt(), 2) << endl << endl; // Charge distribution Map<UInt, UInt> charges; for (Size i = 0; i < feat.size(); ++i) { charges[feat[i].getCharge()]++; } os << "Charge distribution" << endl; for (Map<UInt, UInt>::const_iterator it = charges.begin(); it != charges.end(); ++it) { os << "charge " << it->first << ": " << it->second << endl; } } else if (in_type == FileTypes::CONSENSUSXML) //consensus features { map<Size, UInt> num_consfeat_of_size; for (ConsensusMap::const_iterator cmit = cons.begin(); cmit != cons.end(); ++cmit) { ++num_consfeat_of_size[cmit->size()]; } os << endl << "Number of consensus features:" << endl; for (map<Size, UInt>::reverse_iterator i = num_consfeat_of_size.rbegin(); i != num_consfeat_of_size.rend(); ++i) { os << " of size " << setw(2) << i->first << ": " << setw(6) << i->second << endl; } os << " total: " << setw(6) << cons.size() << endl << endl; os << "Ranges:" << endl << " retention time: " << String::number(cons.getMin()[Peak2D::RT], 2) << " : " << String::number(cons.getMax()[Peak2D::RT], 2) << endl << " mass-to-charge: " << String::number(cons.getMin()[Peak2D::MZ], 2) << " : " << String::number(cons.getMax()[Peak2D::MZ], 2) << endl << " intensity: " << String::number(cons.getMinInt(), 2) << " : " << String::number(cons.getMaxInt(), 2) << endl; // file descriptions const ConsensusMap::FileDescriptions& descs = cons.getFileDescriptions(); if (!descs.empty()) { os << endl << "File descriptions:" << endl; for (ConsensusMap::FileDescriptions::const_iterator it = descs.begin(); it != descs.end(); ++it) { os << " - " << it->second.filename << endl << " identifier: " << it->first << endl << " label : " << it->second.label << endl << " size : " << it->second.size << endl; } } } os << endl << "-- Summary Statistics --" << endl << endl; } if (in_type == FileTypes::FEATUREXML) //features { feat.sortByRT(); vector<double> slice_stats; Size n = getIntOption_("n"); Size begin = 0; Size end = 0; os << "#slice\tRT_begin\tRT_end\tnumber_of_features\ttic\t" << "int_mean\tint_stddev\tint_min\tint_max\tint_median\tint_lowerq\tint_upperq\t" << "mz_mean\tmz_stddev\tmz_min\tmz_max\tmz_median\tmz_lowerq\tmz_upperq\t" << "width_mean\twidth_stddev\twidth_min\twidth_max\twidth_median\twidth_lowerq\twidth_upperq\t" << "qual_mean\tqual_stddev\tqual_min\tqual_max\tqual_median\tqual_lowerq\tqual_upperq\t" << "rt_qual_mean\trt_qual_stddev\trt_qual_min\trt_qual_max\trt_qual_median\trt_qual_lowerq\trt_qual_upperq\t" << "mz_qual_mean\tmz_qual_stddev\tmz_qual_min\tmz_qual_max\tmz_qual_median\tmz_qual_lowerq\tmz_qual_upperq" << endl; double rt_begin = 0.0; for (Size slice = 0; slice < n; ++slice) { // Determine slice boundaries. double rt_end = feat.back().getRT() / (double)n * (slice + 1); for (end = begin; end < feat.size() && feat[end].getRT() < rt_end; ++end) {} // Compute statistics on all features in this slice. slice_stats = sliceStatistics(feat, begin, end); // Write the beginning and end of the slices to the output as well as the slice index. os << slice << "\t" << rt_begin << "\t" << rt_end << "\t" << end - begin << "\t"; // Write the statistics as a line of an csv file copy(slice_stats.begin(), slice_stats.end(), ostream_iterator<double>(os, "\t")); os << endl; begin = end; rt_begin = rt_end; } } else if (in_type == FileTypes::CONSENSUSXML) //consensus features { Size size = cons.size(); vector<double> intensities; intensities.reserve(size); vector<double> qualities(size); qualities.reserve(size); vector<double> widths(size); widths.reserve(size); vector<double> rt_delta_by_elems; vector<double> rt_aad_by_elems; vector<double> rt_aad_by_cfs; rt_aad_by_cfs.reserve(size); vector<double> mz_delta_by_elems; vector<double> mz_aad_by_elems; vector<double> mz_aad_by_cfs; mz_aad_by_cfs.reserve(size); vector<double> it_delta_by_elems; vector<double> it_aad_by_elems; vector<double> it_aad_by_cfs; it_aad_by_cfs.reserve(size); for (ConsensusMap::const_iterator cm_iter = cons.begin(); cm_iter != cons.end(); ++cm_iter) { double rt_aad = 0; double mz_aad = 0; double it_aad = 0; intensities.push_back(cm_iter->getIntensity()); qualities.push_back(cm_iter->getQuality()); widths.push_back(cm_iter->getWidth()); for (ConsensusFeature::HandleSetType::const_iterator hs_iter = cm_iter->begin(); hs_iter != cm_iter->end(); ++hs_iter) { double rt_diff = hs_iter->getRT() - cm_iter->getRT(); rt_delta_by_elems.push_back(rt_diff); if (rt_diff < 0) { rt_diff = -rt_diff; } rt_aad_by_elems.push_back(rt_diff); rt_aad += rt_diff; double mz_diff = hs_iter->getMZ() - cm_iter->getMZ(); mz_delta_by_elems.push_back(mz_diff); if (mz_diff < 0) { mz_diff = -mz_diff; } mz_aad_by_elems.push_back(mz_diff); mz_aad += mz_diff; double it_ratio = hs_iter->getIntensity() / (cm_iter->getIntensity() ? cm_iter->getIntensity() : 1.); it_delta_by_elems.push_back(it_ratio); if (it_ratio < 1.) { it_ratio = 1. / it_ratio; } it_aad_by_elems.push_back(it_ratio); it_aad += it_ratio; } if (!cm_iter->empty()) { rt_aad /= cm_iter->size(); mz_aad /= cm_iter->size(); it_aad /= cm_iter->size(); } // otherwise rt_aad etc. are 0 anyway rt_aad_by_cfs.push_back(rt_aad); mz_aad_by_cfs.push_back(mz_aad); it_aad_by_cfs.push_back(it_aad); } OpenMS::SomeStatistics some_statistics; os.precision(writtenDigits(ConsensusFeature::IntensityType())); os << "Intensities of consensus features:" << endl << some_statistics(intensities) << endl; os.precision(writtenDigits(ConsensusFeature::QualityType())); os << "Qualities of consensus features:" << endl << some_statistics(qualities) << endl; os.precision(writtenDigits(ConsensusFeature::CoordinateType())); os << "Retention time differences ( element-center, weight 1 per element):" << endl << some_statistics(rt_delta_by_elems) << endl; os << "Absolute retention time differences ( |element-center|, weight 1 per element):" << endl << some_statistics(rt_aad_by_elems) << endl; os << "Average absolute differences of retention time within consensus features ( |element-center|, weight 1 per consensus features):" << endl << some_statistics(rt_aad_by_cfs) << endl; os.precision(writtenDigits(ConsensusFeature::CoordinateType())); os << "Mass-to-charge differences ( element-center, weight 1 per element):" << endl << some_statistics(mz_delta_by_elems) << endl; os << "Absolute differences of mass-to-charge ( |element-center|, weight 1 per element):" << endl << some_statistics(mz_aad_by_elems) << endl; os << "Average absolute differences of mass-to-charge within consensus features ( |element-center|, weight 1 per consensus features):" << endl << some_statistics(mz_aad_by_cfs) << endl; os.precision(writtenDigits(ConsensusFeature::IntensityType())); os << "Intensity ratios ( element/center, weight 1 per element):" << endl << some_statistics(it_delta_by_elems) << endl; os << "Relative intensity error ( max{(element/center),(center/element)}, weight 1 per element):" << endl << some_statistics(it_aad_by_elems) << endl; os << "Average relative intensity error within consensus features ( max{(element/center),(center/element)}, weight 1 per consensus features):" << endl << some_statistics(it_aad_by_cfs) << endl; } return EXECUTION_OK; }
void Doodad::Save(ostream& File)const{ File.write(Id,4u); File.write((char*)&Z,4u); File.write((char*)&X,4u); File.write((char*)&Y,4u); }
boolean ScrollerCode::Definition (ostream& out) { boolean ok = true; if ( _emitProperty || _emitInstanceDecls || _emitForward || _emitClassHeaders || _emitHeaders ) { return CodeView::Definition(out); } else if (_emitExpHeader) { InteractorComp* icomp = GetIntComp(); MemberNameVar* mnamer = icomp->GetMemberNameVar(); SubclassNameVar* snamer = icomp->GetClassNameVar(); if (!snamer->IsSubclass()) { if ( _scope && mnamer->GetExport() && !_namelist->Search("scroller") ) { _namelist->Append("scroller"); out << "#include <InterViews/scroller.h>\n"; } } else { ok = ok && CodeView::Definition(out); } } else if (_emitCorehHeader) { InteractorComp* icomp = GetIntComp(); SubclassNameVar* snamer = icomp->GetClassNameVar(); const char* subclass = snamer->GetName(); if (snamer->IsSubclass() && strcmp(subclass, _classname) == 0) { if (!_namelist->Search("scroller")) { _namelist->Append("scroller"); out << "#include <InterViews/scroller.h>\n"; } } } else if (_emitInstanceInits) { InteractorComp* icomp = GetIntComp(); InteractorComp* ctarget = nil; const char* mname = icomp->GetMemberNameVar()->GetName(); MemberNameVar* mnamer = (MemberNameVar*) icomp->GetState( "AdjusteeVar" ); const char* scrollee = mnamer->GetName(); if (*scrollee == '\0') { if (_err_count < 10) { strcat(_errbuf, mname); strcat(_errbuf, " has undefined scrolling target.\n"); _err_count++; } return false; } else if (!Search(mnamer, ctarget)) { if (_err_count < 10) { strcat(_errbuf, mname); strcat( _errbuf, "'s scrolling target is not in the same hierarchy.\n" ); _err_count++; } return false; } else if (ctarget != nil && !icomp->IsRelatableTo(ctarget)) { if (_err_count < 10) { strcat(_errbuf, mname); strcat( _errbuf, "'s adjusting target is not subclassed nor adjustable.\n" ); _err_count++; } return false; } if (_instancelist->Find((void*) scrollee)) { if (!_instancelist->Find((void*) mname)) { _instancelist->Append(new UList((void*)mname)); scrollee = (*scrollee == '\0') ? "nil" : scrollee; BeginInstantiate(out); out << "("; InstanceName(out); out << scrollee << ")"; EndInstantiate(out); _icomplete = true; } } else { _icomplete = false; } } else if ( _emitBSDecls || _emitBSInits || _emitFunctionDecls || _emitFunctionInits ) { return true; } else if ( _emitCoreDecls || _emitCoreInits || _emitClassDecls || _emitClassInits ) { ok = ok && CodeView::Definition(out); } else if (_emitMain) { ok = ok && CodeView::Definition(out); } return out.good() && ok; }
inline void flush() const { if (o != NULL) o->flush(); }
// Write int in Least Significant bytes void writeIntLsb(ostream &out, long l, int size) { if (size <= 0) return; out.put(l&255); writeIntLsb(out, l>>8, size-1); }
void EngAlmanac::dump(ostream& s, bool checkFlag) const { ios::fmtflags oldFlags = s.flags(); s.fill(' '); s << "****************************************************************" << "***************" << endl << "Broadcast Almanac (Engineering Units)" << endl << endl; s << endl << " Iono Parameters" << endl << endl; s << "Alpha: " << scientific << setprecision(6); for (int i=0; i<4; i++) s << setw(13) << alpha[i] << " "; s << " various" << endl; s << " Beta: " << fixed << setprecision(1); for (int i=0; i<4; i++) s << setw(13) << beta[i] << " "; s << " various" << endl; s << endl << " UTC Paramters" << endl << endl; s << scientific << setprecision(8) << "A0: " << setw(15) << A0 << " sec" << endl << "A1: " << setw(15) << A1 << " sec/sec" << endl << fixed << setprecision(1) << "dt_ls: " << setw(15) << dt_ls << " sec" << endl << "t_ot: " << setw(15) << t_ot << " sec" << endl << "wn_t: " << setw(15) << wn_t << " week" << endl << "wn_lsf " << setw(15) << wn_lsf << " week" << endl << "dn: " << setw(15) << (int)dn << " days" << endl << "dt_lsf: " << setw(15) << dt_lsf << " sec" << endl; s << endl << " Orbit Parameters" << endl << endl; for (AlmOrbits::const_iterator i = almPRN.begin(); i != almPRN.end(); i++) s<< scientific << (*i).second; s << endl << " Special Message" << endl << endl; StringUtils::hexDumpData(s, special_msg); s << endl << " Page 25 Health, AS, & SV config" << endl << endl; s << "Toa: " << setfill(' ') << setw(8) << t_oa << ", week: " << setw(5) << wn_a << " (" << alm_wk << ")" << endl << endl << "PRN health AS cfg PRN health AS cfg" << endl; string bits[33]; for (SVBitsMap::const_iterator i = health.begin(); i != health.end(); i++) { int prn = i->first; if (prn >= 1 && prn <= 32) bits[prn] = int2bin(i->second, 6); } for (SVBitsMap::const_iterator i = SV_config.begin(); i != SV_config.end(); i++) { int prn = i->first; if (prn >= 1 && prn <= 32) { bits[prn] += " " + int2bin(i->second, 4); bits[prn].insert(9, " "); } } for (int i=1; i<=16; i++) s << setw(2) << i << " " << bits[i] << " " << setw(2) << i+16 << " " << bits[i+16] << endl; s << endl; if (checkFlag) check(s); s << endl; s.flags(oldFlags); } // end of dump()
/*static*/ void ast_node::output_annot(ostream& stream,int level,const char* annot) { for (int i = 0;i < level;++i) stream.put('\t'); stream << '[' << annot << "]\n"; }
// Write int in Least Significant bytes void writeIntLsb(ostream &out, long l, int size) { if (size <= 0) return; out.put((char)(l & 0xFF)); writeIntLsb(out, l>>8, size-1); }
/** * Write the synapse data to the stream * @param[in] os The filestream to write */ void ISynapse::write( ostream& os ) { os.write( reinterpret_cast<const char*>(&summationCoord), sizeof(summationCoord) ); os.write( reinterpret_cast<const char*>(&synapseCoord), sizeof(synapseCoord) ); os.write( reinterpret_cast<const char*>(&deltaT), sizeof(deltaT) ); os.write( reinterpret_cast<const char*>(&W), sizeof(W) ); os.write( reinterpret_cast<const char*>(&psr), sizeof(psr) ); os.write( reinterpret_cast<const char*>(&decay), sizeof(decay) ); os.write( reinterpret_cast<const char*>(&total_delay), sizeof(total_delay) ); os.write( reinterpret_cast<const char*>(delayQueue), sizeof(uint32_t) ); os.write( reinterpret_cast<const char*>(&delayIdx), sizeof(delayIdx) ); os.write( reinterpret_cast<const char*>(&ldelayQueue), sizeof(ldelayQueue) ); os.write( reinterpret_cast<const char*>(&type), sizeof(type) ); os.write( reinterpret_cast<const char*>(&tau), sizeof(tau) ); os.write( reinterpret_cast<const char*>(&r), sizeof(r) ); os.write( reinterpret_cast<const char*>(&u), sizeof(u) ); os.write( reinterpret_cast<const char*>(&D), sizeof(D) ); os.write( reinterpret_cast<const char*>(&U), sizeof(U) ); os.write( reinterpret_cast<const char*>(&F), sizeof(F) ); os.write( reinterpret_cast<const char*>(&lastSpike), sizeof(lastSpike) ); }
void MemoryMap::pagesizealign(ostream &out) { size_t at = out.tellp(); size_t offs = at % pagesize; if(offs) { out.seekp(pagesize - offs, ios::cur); } }
void Auto::write(ostream& os, Token token) { os.write((char*)&token, sizeof(token)); }
static void write_64(hash_t h, ostream &out) { std::ios_base::fmtflags original_flags = out.flags(); out << "0x" << (hex) << h << "ULL"; out.flags(original_flags); }
void Auto::write(ostream& os, Tokens tokens) { os.write((char*)&tokens, sizeof(tokens)); }
void outputPhrasePair(const PhraseAlignmentCollection &phrasePair, float totalCount, int distinctCount, ostream &phraseTableFile, bool isSingleton ) { if (phrasePair.size() == 0) return; const PhraseAlignment &bestAlignment = findBestAlignment( phrasePair ); // compute count float count = 0; for(size_t i=0; i<phrasePair.size(); i++) { count += phrasePair[i]->count; } // compute domain counts map< string, float > domainCount; if (domainFlag) { for(size_t i=0; i<phrasePair.size(); i++) { string d = domain->getDomainOfSentence( phrasePair[i]->sentenceId ); if (domainCount.find( d ) == domainCount.end()) domainCount[ d ] = phrasePair[i]->count; else domainCount[ d ] += phrasePair[i]->count; } } // collect count of count statistics if (goodTuringFlag || kneserNeyFlag) { totalDistinct++; int countInt = count + 0.99999; if(countInt <= COC_MAX) countOfCounts[ countInt ]++; } // compute PCFG score float pcfgScore = 0; if (pcfgFlag && !inverseFlag) { float pcfgSum = 0; for(size_t i=0; i<phrasePair.size(); ++i) { pcfgSum += phrasePair[i]->pcfgSum; } pcfgScore = pcfgSum / count; } // output phrases const PHRASE &phraseS = phrasePair[0]->GetSource(); const PHRASE &phraseT = phrasePair[0]->GetTarget(); // do not output if hierarchical and count below threshold if (hierarchicalFlag && count < minCountHierarchical) { for(size_t j=0; j<phraseS.size()-1; j++) { if (isNonTerminal(vcbS.getWord( phraseS[j] ))) return; } } // source phrase (unless inverse) if (! inverseFlag) { printSourcePhrase(phraseS, phraseT, bestAlignment, phraseTableFile); phraseTableFile << " ||| "; } // target phrase printTargetPhrase(phraseS, phraseT, bestAlignment, phraseTableFile); phraseTableFile << " ||| "; // source phrase (if inverse) if (inverseFlag) { printSourcePhrase(phraseS, phraseT, bestAlignment, phraseTableFile); phraseTableFile << " ||| "; } // lexical translation probability if (lexFlag) { double lexScore = computeLexicalTranslation( phraseS, phraseT, bestAlignment); phraseTableFile << maybeLogProb( lexScore ); } // unaligned word penalty if (unalignedFlag) { double penalty = computeUnalignedPenalty( phraseS, phraseT, bestAlignment); phraseTableFile << " " << maybeLogProb( penalty ); } // unaligned function word penalty if (unalignedFWFlag) { double penalty = computeUnalignedFWPenalty( phraseS, phraseT, bestAlignment); phraseTableFile << " " << maybeLogProb( penalty ); } if (singletonFeature) { phraseTableFile << " " << (isSingleton ? 1 : 0); } if (crossedNonTerm && !inverseFlag) { phraseTableFile << " " << calcCrossedNonTerm(phraseS, bestAlignment); } // target-side PCFG score if (pcfgFlag && !inverseFlag) { phraseTableFile << " " << maybeLogProb( pcfgScore ); } // domain count features if (domainFlag) { if (domainSparseFlag) { // sparse, subset if (domainSubsetFlag) { typedef vector< string >::const_iterator I; phraseTableFile << " doms"; for (I i = domain->list.begin(); i != domain->list.end(); i++ ) { if (domainCount.find( *i ) != domainCount.end() ) { phraseTableFile << "_" << *i; } } phraseTableFile << " 1"; } // sparse, indicator or ratio else { typedef map< string, float >::const_iterator I; for (I i=domainCount.begin(); i != domainCount.end(); i++) { if (domainRatioFlag) { phraseTableFile << " domr_" << i->first << " " << (i->second / count); } else { phraseTableFile << " dom_" << i->first << " 1"; } } } } // core, subset else if (domainSubsetFlag) { if (domain->list.size() > 6) { cerr << "ERROR: too many domains for core domain subset features\n"; exit(1); } size_t bitmap = 0; for(size_t bit = 0; bit < domain->list.size(); bit++) { if (domainCount.find( domain->list[ bit ] ) != domainCount.end()) { bitmap += 1 << bit; } } for(size_t i = 1; i < (1 << domain->list.size()); i++) { phraseTableFile << " " << maybeLogProb( (bitmap == i) ? 2.718 : 1 ); } } // core, indicator or ratio else { typedef vector< string >::const_iterator I; for (I i = domain->list.begin(); i != domain->list.end(); i++ ) { if (domainCount.find( *i ) == domainCount.end() ) { phraseTableFile << " " << maybeLogProb( 1 ); } else if (domainRatioFlag) { phraseTableFile << " " << maybeLogProb( exp( domainCount[ *i ] / count ) ); } else { phraseTableFile << " " << maybeLogProb( 2.718 ); } } } } phraseTableFile << " ||| "; // alignment info for non-terminals if (! inverseFlag) { if (hierarchicalFlag) { // always output alignment if hiero style, but only for non-terms // (eh: output all alignments, needed for some feature functions) assert(phraseT.size() == bestAlignment.alignedToT.size() + 1); std::vector<std::string> alignment; for(size_t j = 0; j < phraseT.size() - 1; j++) { if (isNonTerminal(vcbT.getWord( phraseT[j] ))) { if (bestAlignment.alignedToT[ j ].size() != 1) { cerr << "Error: unequal numbers of non-terminals. Make sure the text does not contain words in square brackets (like [xxx])." << endl; phraseTableFile.flush(); assert(bestAlignment.alignedToT[ j ].size() == 1); } int sourcePos = *(bestAlignment.alignedToT[ j ].begin()); //phraseTableFile << sourcePos << "-" << j << " "; std::stringstream point; point << sourcePos << "-" << j; alignment.push_back(point.str()); } else { set<size_t>::iterator setIter; for(setIter = (bestAlignment.alignedToT[j]).begin(); setIter != (bestAlignment.alignedToT[j]).end(); setIter++) { int sourcePos = *setIter; //phraseTableFile << sourcePos << "-" << j << " "; std::stringstream point; point << sourcePos << "-" << j; alignment.push_back(point.str()); } } } // now print all alignments, sorted by source index sort(alignment.begin(), alignment.end()); for (size_t i = 0; i < alignment.size(); ++i) { phraseTableFile << alignment[i] << " "; } } else if (wordAlignmentFlag) { // alignment info in pb model for(size_t j=0; j<bestAlignment.alignedToT.size(); j++) { const set< size_t > &aligned = bestAlignment.alignedToT[j]; for (set< size_t >::const_iterator p(aligned.begin()); p != aligned.end(); ++p) { phraseTableFile << *p << "-" << j << " "; } } } } // counts phraseTableFile << " ||| " << totalCount << " " << count; if (kneserNeyFlag) phraseTableFile << " " << distinctCount; // nt lengths if (outputNTLengths) { phraseTableFile << " ||| "; if (!inverseFlag) { map<size_t, map<size_t, float> > sourceProb, targetProb; // 1st sourcePos, 2nd = length, 3rd = prob calcNTLengthProb(phrasePair, sourceProb, targetProb); outputNTLengthProbs(phraseTableFile, sourceProb, "S"); outputNTLengthProbs(phraseTableFile, targetProb, "T"); } } phraseTableFile << endl; }
inline void Plotter::emit_byte(int c) { outstream->put((unsigned char) c); }
inline void DepthExporter::exportPlyFace(ostream& ply, unsigned int a, unsigned int b, unsigned int c) { ply << (unsigned char) 3; ply.write(reinterpret_cast<char*>(&a), sizeof(unsigned int)); ply.write(reinterpret_cast<char*>(&b), sizeof(unsigned int)); ply.write(reinterpret_cast<char*>(&c), sizeof(unsigned int)); }