/// Returns the absolute pathnames of all lyx local sockets in /// file system encoding. /// Parts stolen from lyx::support::DirList(). FileNameList lyxSockets(string const & dir, string const & pid) { FileNameList dirlist; FileName dirpath(dir + "/"); if (!dirpath.exists() || !dirpath.isDirectory()) { lyxerr << dir << " does not exist or is not a directory." << endl; return dirlist; } FileNameList dirs = dirpath.dirList(""); FileNameList::const_iterator it = dirs.begin(); FileNameList::const_iterator end = dirs.end(); for (; it != end; ++it) { if (!it->isDirectory()) continue; string const tmpdir = it->absFileName(); if (!contains(tmpdir, "lyx_tmpdir" + pid)) continue; FileName lyxsocket(tmpdir + "/lyxsocket"); if (lyxsocket.exists()) dirlist.push_back(lyxsocket); } return dirlist; }
void PhotoArchive::buildArchive(const std::string& filename, const FileNameList& imageList, unsigned int thumbnailSize, unsigned int maximumSize, bool /*compressed*/) { PhotoIndexList photoIndex; photoIndex.reserve(imageList.size()); for(FileNameList::const_iterator fitr=imageList.begin(); fitr!=imageList.end(); ++fitr) { PhotoHeader header; // set name strncpy(header.filename,fitr->c_str(),255); header.filename[255]=0; header.thumbnail_s = thumbnailSize; header.thumbnail_t = thumbnailSize; header.thumbnail_position = 0; header.fullsize_s = thumbnailSize; header.fullsize_t = thumbnailSize; header.fullsize_position = 0; photoIndex.push_back(header); } std::cout<<"Building photo archive containing "<<photoIndex.size()<<" pictures"<<std::endl; // open up the archive for writing to osgDB::ofstream out(filename.c_str(), std::ios::out | std::ios::binary); // write out file indentifier. out.write(FILE_IDENTIFER.c_str(),FILE_IDENTIFER.size()); unsigned int numPhotos = photoIndex.size(); out.write((char*)&numPhotos,sizeof(unsigned int)); // write the photo index to ensure we can the correct amount of space // available. unsigned int startOfPhotoIndex = out.tellp(); out.write((char*)&photoIndex.front(),sizeof(PhotoHeader)*photoIndex.size()); unsigned int photoCount=1; for(PhotoIndexList::iterator pitr=photoIndex.begin(); pitr!=photoIndex.end(); ++pitr,++photoCount) { PhotoHeader& photoHeader = *pitr; std::cout<<"Processing image "<<photoCount<<" of "<< photoIndex.size()<<" filename="<< photoHeader.filename << std::endl; std::cout<<" reading image...";std::cout.flush(); osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile(photoHeader.filename); std::cout<<"done."<< std::endl; photoHeader.original_s = image->s(); photoHeader.original_t = image->t(); { std::cout<<" creating thumbnail image..."; // first need to rescale image to the require thumbnail size unsigned int newTotalSize = image->computeRowWidthInBytes(thumbnailSize,image->getPixelFormat(),image->getDataType(),image->getPacking())* thumbnailSize; // need to sort out what size to really use... unsigned char* newData = new unsigned char [newTotalSize]; if (!newData) { // should we throw an exception??? Just return for time being. osg::notify(osg::FATAL) << "Error scaleImage() did not succeed : out of memory."<<newTotalSize<<std::endl; return; } osg::PixelStorageModes psm; psm.pack_alignment = image->getPacking(); psm.pack_row_length = image->getRowLength(); psm.unpack_alignment = image->getPacking(); GLint status = osg::gluScaleImage(&psm, image->getPixelFormat(), image->s(), image->t(), image->getDataType(), image->data(), thumbnailSize, thumbnailSize, image->getDataType(), newData); if (status!=0) { delete [] newData; osg::notify(osg::WARN) << "Error scaleImage() did not succeed : errorString = "<<osg::gluErrorString((GLenum)status)<<std::endl; return; } // now set up the photo header. photoHeader.thumbnail_s = thumbnailSize; photoHeader.thumbnail_t = thumbnailSize; photoHeader.thumbnail_position = (unsigned int)out.tellp(); // set up image header ImageHeader imageHeader; imageHeader.s = thumbnailSize; imageHeader.t = thumbnailSize; imageHeader.internalTextureformat = image->getInternalTextureFormat(); imageHeader.pixelFormat = image->getPixelFormat(); imageHeader.type = image->getDataType(); imageHeader.size = newTotalSize; // write out image header and image data. out.write((char*)&imageHeader,sizeof(ImageHeader)); out.write((char*)newData,imageHeader.size); delete [] newData; std::cout<<"done."<< std::endl; } { std::cout<<" creating fullsize image...";std::cout.flush(); photoHeader.fullsize_s = osg::minimum((unsigned int)image->s(),maximumSize); photoHeader.fullsize_t = osg::minimum((unsigned int)image->t(),maximumSize); photoHeader.fullsize_position = (unsigned int)out.tellp(); // first need to rescale image to the require thumbnail size unsigned int newTotalSize = image->computeRowWidthInBytes(photoHeader.fullsize_s,image->getPixelFormat(),image->getDataType(),image->getPacking())* photoHeader.fullsize_t; // need to sort out what size to really use... unsigned char* newData = new unsigned char [newTotalSize]; if (!newData) { // should we throw an exception??? Just return for time being. osg::notify(osg::FATAL) << "Error scaleImage() did not succeed : out of memory."<<newTotalSize<<std::endl; return; } osg::PixelStorageModes psm; psm.pack_alignment = image->getPacking(); psm.pack_row_length = image->getRowLength(); psm.unpack_alignment = image->getPacking(); GLint status = osg::gluScaleImage(&psm, image->getPixelFormat(), image->s(), image->t(), image->getDataType(), image->data(), photoHeader.fullsize_s, photoHeader.fullsize_t, image->getDataType(), newData); if (status!=0) { delete [] newData; osg::notify(osg::WARN) << "Error scaleImage() did not succeed : errorString = "<<osg::gluErrorString((GLenum)status)<<std::endl; return; } ImageHeader imageHeader; imageHeader.s = photoHeader.fullsize_s; imageHeader.t = photoHeader.fullsize_t; imageHeader.internalTextureformat = image->getInternalTextureFormat(); imageHeader.pixelFormat = image->getPixelFormat(); imageHeader.type = image->getDataType(); imageHeader.size = newTotalSize; out.write((char*)&imageHeader,sizeof(ImageHeader)); out.write((char*)newData,imageHeader.size); //out.write((char*)image->data(),imageHeader.size); delete [] newData; std::cout<<"done."<< std::endl; } } // rewrite photo index now it has the correct sizes set out.seekp(startOfPhotoIndex); out.write((char*)&photoIndex.front(),sizeof(PhotoHeader)*photoIndex.size()); }
int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is an application for collecting a set of seperate files into a single archive file that can be later read in OSG applications.."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); // if user request help write it out to cout. if (arguments.read("-h") || arguments.read("--help")) { arguments.getApplicationUsage()->write(std::cout); return 1; } std::string archiveFilename; while (arguments.read("-a",archiveFilename) || arguments.read("--archive",archiveFilename)) { } bool insert = false; while (arguments.read("-i") || arguments.read("--insert")) { insert = true; } bool extract = false; while (arguments.read("-e") || arguments.read("--extract")) { extract = true; } bool list = false; while (arguments.read("-l") || arguments.read("--list")) { list = true; } typedef std::vector<std::string> FileNameList; FileNameList files; for(int pos=1;pos<arguments.argc();++pos) { if (!arguments.isOption(pos)) { if (insert) { std::string filePath = osgDB::findDataFile(arguments[pos]); osgDB::FileType fileType = osgDB::fileType(filePath); if (fileType==osgDB::REGULAR_FILE) { files.push_back(arguments[pos]); } else if (fileType==osgDB::DIRECTORY) { osgDB::DirectoryContents directory = osgDB::getDirectoryContents(arguments[pos]); osgDB::DirectoryContents::iterator it = directory.begin(); while( it != directory.end()) { files.push_back(filePath + "/" + (*it)); ++it; } } } else { files.push_back(arguments[pos]); } } } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } if (archiveFilename.empty()) { std::cout<<"Please specify an archive name using --archive filename"<<std::endl; return 1; } if (!insert && !extract && !list) { std::cout<<"Please specify an operation on the archive, either --insert, --extract or --list"<<std::endl; return 1; } if (insert && extract) { std::cout<<"Cannot insert and extract files from the archive at one time, please use either --insert or --extract."<<std::endl; return 1; } osg::ref_ptr<osgDB::Archive> archive; if (insert) { archive = osgDB::openArchive(archiveFilename, osgDB::Archive::WRITE); if (archive.valid()) { for (FileNameList::iterator itr=files.begin(); itr!=files.end(); ++itr) { std::cout<<"reading "<<*itr<<std::endl; osg::ref_ptr<osg::Object> obj = osgDB::readObjectFile(*itr); if (obj.valid()) { std::cout<<" write to archive "<<*itr<<std::endl; archive->writeObject(*obj, *itr); } } } } else { archive = osgDB::openArchive(archiveFilename, osgDB::Archive::READ); if (extract && archive.valid()) { for (FileNameList::iterator itr=files.begin(); itr!=files.end(); ++itr) { osg::Timer_t start = osg::Timer::instance()->tick(); osgDB::ReaderWriter::ReadResult result = archive->readObject(*itr); osg::ref_ptr<osg::Object> obj = result.getObject(); std::cout<<"readObejct time = "<<osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick())<<std::endl; if (obj.valid()) { osgDB::writeObjectFile(*obj, *itr); } } } } if (list && archive.valid()) { std::cout<<"List of files in archive:"<<std::endl; osgDB::Archive::FileNameList fileNames; if (archive->getFileNames(fileNames)) { for(osgDB::Archive::FileNameList::const_iterator itr=fileNames.begin(); itr!=fileNames.end(); ++itr) { std::cout<<" "<<*itr<<std::endl; } } std::cout<<std::endl; std::cout<<"Master file "<<archive->getMasterFileName()<<std::endl; } return 0; }
int main(int argc, char *argv[]) { using Teuchos::RCP; // Communicators Teuchos::GlobalMPISession mpiSession(&argc, &argv); const Albany_MPI_Comm nativeComm = Albany_MPI_COMM_WORLD; const RCP<const Teuchos::Comm<int> > teuchosComm = Albany::createTeuchosCommFromMpiComm(nativeComm); const RCP<const Epetra_Comm> epetraComm = Albany::createEpetraCommFromMpiComm(nativeComm); // Standard output const RCP<Teuchos::FancyOStream> out = Teuchos::VerboseObjectBase::getDefaultOStream(); // Parse command-line argument for input file const std::string firstArg = (argc > 1) ? argv[1] : ""; if (firstArg.empty() || firstArg == "--help") { *out << "AlbanyRBGen input-file-path\n"; return 0; } const std::string inputFileName = argv[1]; // Parse XML input file const RCP<Teuchos::ParameterList> topLevelParams = Teuchos::createParameterList("Albany Parameters"); Teuchos::updateParametersFromXmlFileAndBroadcast(inputFileName, topLevelParams.ptr(), *teuchosComm); // Create base discretization, used to retrieve the snapshot map and output the basis const Teuchos::RCP<Teuchos::ParameterList> baseTopLevelParams(new Teuchos::ParameterList(*topLevelParams)); const RCP<Albany::AbstractDiscretization> baseDisc = Albany::discretizationNew(baseTopLevelParams, epetraComm); const RCP<Teuchos::ParameterList> rbgenParams = Teuchos::sublist(topLevelParams, "Reduced Basis", /*sublistMustExist =*/ true); typedef Teuchos::Array<std::string> FileNameList; FileNameList snapshotFiles; { const RCP<Teuchos::ParameterList> snapshotSourceParams = Teuchos::sublist(rbgenParams, "Snapshot Sources"); snapshotFiles = snapshotSourceParams->get("File Names", snapshotFiles); } typedef Teuchos::Array<RCP<Albany::STKDiscretization> > DiscretizationList; DiscretizationList discretizations; if (snapshotFiles.empty()) { discretizations.push_back(Teuchos::rcp_dynamic_cast<Albany::STKDiscretization>(baseDisc, /*throw_on_fail =*/ true)); } else { discretizations.reserve(snapshotFiles.size()); for (FileNameList::const_iterator it = snapshotFiles.begin(), it_end = snapshotFiles.end(); it != it_end; ++it) { const Teuchos::RCP<Teuchos::ParameterList> localTopLevelParams(new Teuchos::ParameterList(*topLevelParams)); { // Replace discretization parameters to read snapshot file Teuchos::ParameterList localDiscParams; localDiscParams.set("Method", "Ioss"); localDiscParams.set("Exodus Input File Name", *it); localTopLevelParams->set("Discretization", localDiscParams); } const RCP<Albany::AbstractDiscretization> disc = Albany::discretizationNew(localTopLevelParams, epetraComm); discretizations.push_back(Teuchos::rcp_dynamic_cast<Albany::STKDiscretization>(disc, /*throw_on_fail =*/ true)); } } typedef Teuchos::Array<RCP<MOR::EpetraMVSource> > SnapshotSourceList; SnapshotSourceList snapshotSources; for (DiscretizationList::const_iterator it = discretizations.begin(), it_end = discretizations.end(); it != it_end; ++it) { snapshotSources.push_back(Teuchos::rcp(new Albany::StkEpetraMVSource(*it))); } MOR::ConcatenatedEpetraMVSource snapshotSource(*baseDisc->getMap(), snapshotSources); *out << "Total snapshot count = " << snapshotSource.vectorCount() << "\n"; const Teuchos::RCP<Epetra_MultiVector> rawSnapshots = snapshotSource.multiVectorNew(); // Isolate Dirichlet BC RCP<const Epetra_Vector> blockVector; if (rbgenParams->isSublist("Blocking")) { const RCP<const Teuchos::ParameterList> blockingParams = Teuchos::sublist(rbgenParams, "Blocking"); const Teuchos::Array<int> mySelectedLIDs = getMyBlockLIDs(*blockingParams, *baseDisc); *out << "Selected LIDs = " << mySelectedLIDs << "\n"; blockVector = MOR::isolateUniformBlock(mySelectedLIDs, *rawSnapshots); } // Preprocess raw snapshots const RCP<Teuchos::ParameterList> preprocessingParams = Teuchos::sublist(rbgenParams, "Snapshot Preprocessing"); MOR::SnapshotPreprocessorFactory preprocessorFactory; const Teuchos::RCP<MOR::SnapshotPreprocessor> snapshotPreprocessor = preprocessorFactory.instanceNew(preprocessingParams); snapshotPreprocessor->rawSnapshotSetIs(rawSnapshots); const RCP<const Epetra_MultiVector> modifiedSnapshots = snapshotPreprocessor->modifiedSnapshotSet(); const RCP<const Epetra_Vector> origin = snapshotPreprocessor->origin(); const bool nonzeroOrigin = Teuchos::nonnull(origin); *out << "After preprocessing, " << modifiedSnapshots->NumVectors() << " snapshot vectors and " << static_cast<int>(nonzeroOrigin) << " origin\n"; // By default, compute as many basis vectors as snapshots (void) Teuchos::sublist(rbgenParams, "Reduced Basis Method")->get("Basis Size", modifiedSnapshots->NumVectors()); // Compute reduced basis RBGen::EpetraMVMethodFactory methodFactory; const RCP<RBGen::Method<Epetra_MultiVector, Epetra_Operator> > method = methodFactory.create(*rbgenParams); method->Initialize(rbgenParams, modifiedSnapshots); method->computeBasis(); const RCP<const Epetra_MultiVector> basis = method->getBasis(); *out << "Computed " << basis->NumVectors() << " left-singular vectors\n"; // Compute discarded energy fraction for each left-singular vector // (relative residual energy corresponding to a basis truncation after current vector) const RCP<const RBGen::PODMethod<double> > pod_method = Teuchos::rcp_dynamic_cast<RBGen::PODMethod<double> >(method); const Teuchos::Array<double> singularValues = pod_method->getSingularValues(); *out << "Singular values: " << singularValues << "\n"; const Teuchos::Array<double> discardedEnergyFractions = MOR::computeDiscardedEnergyFractions(singularValues); *out << "Discarded energy fractions: " << discardedEnergyFractions << "\n"; // Output results { // Setup overlapping map and vector const Epetra_Map outputMap = *baseDisc->getOverlapMap(); const Epetra_Import outputImport(outputMap, snapshotSource.vectorMap()); Epetra_Vector outputVector(outputMap, /*zeroOut =*/ false); if (nonzeroOrigin) { const double stamp = -1.0; // Stamps must be increasing outputVector.Import(*origin, outputImport, Insert); baseDisc->writeSolution(outputVector, stamp, /*overlapped =*/ true); } if (Teuchos::nonnull(blockVector)) { const double stamp = -1.0 + std::numeric_limits<double>::epsilon(); TEUCHOS_ASSERT(stamp != -1.0); outputVector.Import(*blockVector, outputImport, Insert); baseDisc->writeSolution(outputVector, stamp, /*overlapped =*/ true); } for (int i = 0; i < basis->NumVectors(); ++i) { const double stamp = -discardedEnergyFractions[i]; // Stamps must be increasing const Epetra_Vector vec(View, *basis, i); outputVector.Import(vec, outputImport, Insert); baseDisc->writeSolution(outputVector, stamp, /*overlapped =*/ true); } } }
int main(int argc, char * argv[]) { using namespace lyx; lyxerr.setStream(cerr); char const * const lyxsocket = getenv("LYXSOCKET"); if (lyxsocket) cmdline::serverAddress = from_local8bit(lyxsocket); CmdLineParser args; args.helper["-h"] = cmdline::h; args.helper["-c"] = cmdline::c; args.helper["-g"] = cmdline::g; args.helper["-n"] = cmdline::n; args.helper["-a"] = cmdline::a; args.helper["-t"] = cmdline::t; args.helper["-p"] = cmdline::p; // Command line failure conditions: if ((!args.parse(argc, argv)) || (args.isset["-c"] && args.isset["-g"]) || (args.isset["-a"] && args.isset["-p"])) { cmdline::usage(); return 1; } scoped_ptr<LyXDataSocket> server; if (!cmdline::serverAddress.empty()) { server.reset(new LyXDataSocket(FileName(to_utf8(cmdline::serverAddress)))); if (!server->connected()) { cerr << "lyxclient: " << "Could not connect to " << to_utf8(cmdline::serverAddress) << endl; return EXIT_FAILURE; } } else { // We have to look for an address. // serverPid can be empty. FileNameList addrs = lyxSockets(to_filesystem8bit(cmdline::mainTmp), cmdline::serverPid); FileNameList::const_iterator addr = addrs.begin(); FileNameList::const_iterator end = addrs.end(); for (; addr != end; ++addr) { // Caution: addr->string() is in filesystem encoding server.reset(new LyXDataSocket(*addr)); if (server->connected()) break; lyxerr << "lyxclient: " << "Could not connect to " << addr->absFileName() << endl; } if (addr == end) { lyxerr << "lyxclient: No suitable server found." << endl; return EXIT_FAILURE; } cerr << "lyxclient: " << "Connected to " << addr->absFileName() << endl; } int const serverfd = server->fd(); IOWatch iowatch; iowatch.addfd(serverfd); // Used to read from server string answer; // Send greeting server->writeln("HELLO:" + to_utf8(cmdline::clientName)); // wait at most 2 seconds until server responds iowatch.wait(2.0); if (iowatch.isset(serverfd) && server->readln(answer)) { if (prefixIs(answer, "BYE:")) { cerr << "lyxclient: Server disconnected." << endl; cout << answer << endl; return EXIT_FAILURE; } } else { cerr << "lyxclient: No answer from server." << endl; return EXIT_FAILURE; } if (args.isset["-g"] || args.isset["-c"]) { server->writeln(to_utf8(cmdline::singleCommand)); iowatch.wait(2.0); if (iowatch.isset(serverfd) && server->readln(answer)) { cout << answer; if (prefixIs(answer, "ERROR:")) return EXIT_FAILURE; return EXIT_SUCCESS; } else { cerr << "lyxclient: No answer from server." << endl; return EXIT_FAILURE; } } // Take commands from stdin iowatch.addfd(0); // stdin bool saidbye = false; while ((!saidbye) && server->connected()) { iowatch.wait(); if (iowatch.isset(0)) { string command; getline(cin, command); if (command.empty()) continue; if (command == "BYE:") { server->writeln("BYE:"); saidbye = true; } else { server->writeln("LYXCMD:" + command); } } if (iowatch.isset(serverfd)) { while(server->readln(answer)) cout << answer << endl; } } return EXIT_SUCCESS; }