TskModule::Status TskExecutableModule::execute(TskFile * fileToAnalyze){
    try
    {
        // Perform macro expansion on command line args.
        std::string arguments = expandArgumentMacros(m_arguments, fileToAnalyze);

        // Split the arguments into a vector of strings.
        Poco::StringTokenizer tokenizer(arguments, " ");

        std::vector<std::string> vectorArgs(tokenizer.begin(), tokenizer.end());

        // Perform macro expansion on our output location
        std::string outFilePath = expandArgumentMacros(m_output, fileToAnalyze);

        // If an output file has been specified we need to ensure that anything
        // written to stdout gets put in the file. This is accomplished by passing
        // a pipe to Poco::Process::launch and reading its contents once the process
        // has terminated.
        if (!outFilePath.empty())
        {
            // Create directories that may be missing along the path.
            std::string outFilePathNoQuote(TskUtilities::stripQuotes(outFilePath));
            Poco::Path outPath(outFilePathNoQuote);
            Poco::File outDir(outPath.parent());
            outDir.createDirectories();

            // Create the output file if it does not exist.
            Poco::File outFile(outFilePathNoQuote);

            if (!outFile.exists())
            {
                outFile.createFile();
            }

            // Create process redirecting its output to a Pipe.
            Poco::Pipe outPipe;

            Poco::ProcessHandle handle = Poco::Process::launch(m_modulePath, vectorArgs, NULL, &outPipe, NULL);
            
            // Copy output from Pipe to the output file.
            Poco::PipeInputStream istr(outPipe);
            Poco::FileOutputStream ostr(outFile.path(), std::ios::out|std::ios::app);

            while (istr)
            {
                Poco::StreamCopier::copyStream(istr, ostr);
            }

            // The process should be finished. Check its exit code.
            int exitCode = Poco::Process::wait(handle);

            if (exitCode != 0)
            {
                // If a module fails we log a warning message and continue.
                std::wstringstream msg;
                msg << L"TskExecutableModule::execute - Module (" << m_modulePath.c_str()
                    << L") failed with exit code: " << exitCode << std::endl;
                LOGWARN(msg.str());
            }
        }
        else
        {
            // No output file was specified.
            Poco::ProcessHandle handle = Poco::Process::launch(m_modulePath, vectorArgs);

            // Wait for the process to complete
            int exitCode = Poco::Process::wait(handle);

            if (exitCode != 0)
            {
                // If a module fails we log a warning message and continue.
                std::wstringstream msg;
                msg << L"TskExecutableModule::execute - Module (" << m_modulePath.c_str()
                    << L") failed with exit code: " << exitCode << std::endl;
                LOGWARN(msg.str());
            }
        }
    }
    catch (Poco::Exception& ex)
    {
        std::wstringstream errorMsg;
        errorMsg << L"TskExecutableModule::execute - Error: " << ex.displayText().c_str() << std::endl;
        LOGERROR(errorMsg.str());
        throw TskException("Module execution failed.");
    }

    return TskModule::OK;
}
double runAlgoSequence(AlgoDescriptor const* descriptor, GMMDesc initialSolution, double initialTime,
	std::string const& outputDir, std::string const& outputFile)
{
	// Initialize output
	std::stringstream pathStream;
	pathStream << outputDir << "/csv";
	boost::filesystem::path outPath(pathStream.str());
	boost::filesystem::create_directories(outPath);
	std::stringstream filenameStream;
	filenameStream << pathStream.str() << "/" << outputFile;
	ioutil::openStatisticFile(filenameStream.str());


	// compute maximum spread
	Vector spreads = (input.points.rowwise().maxCoeff()
					 -input.points.rowwise().minCoeff());
					 
	if (commonSettings().verbose)
		std::cout << "maximum spread is " << spreads.maxCoeff() << std::endl;

	// Initialisation
	double totaltime = initialTime;
	GMMDesc last = initialSolution;

	// handle initial solution
	handleSolution(0, last, totaltime, true);

	// start computation of new algorithm sequence
	std::cout << "starting new algorithm sequence:" << std::endl;
			  
	AlgoDescriptor const* nextAlgo = descriptor;
	std:size_t roundOffset = 0;
	std::vector<std::size_t> finalRounds;
	std::vector<double> finalTimes;
	while (nextAlgo!=NULL)
	{
		std::cout << "creating algorithm from descriptor: "
				  << nextAlgo->tag() << std::endl;
				  
		GMMAlgorithm* algorithm = nextAlgo->create(input);
		algorithm->init(last);
		
		// run current algorithm
		for (std::size_t i=0; i<nextAlgo->steps(); ++i)
		{
			algorithm->run();
			handleSolution(roundOffset+i+1, algorithm->getGMMDesc(),
				algorithm->getRuntime()+totaltime, algorithm->hasChanged());
		}
		
		// Save results and delete algorithm
		last = algorithm->getGMMDesc();
		roundOffset += nextAlgo->steps();
		totaltime += algorithm->getRuntime();
		finalRounds.push_back(roundOffset);
		finalTimes.push_back(totaltime);
		std::cout << "   computation took " << algorithm->getRuntime() << " seconds." << std::endl;

		delete algorithm;

		nextAlgo = nextAlgo->getNext();
	}
	std::cout << std::endl;

	if (ioutil::StatisticFileIsOpen())
	{
		// Store statistics markers
		ioutil::storeStatisticMarkerVector(finalRounds, finalTimes, mincost_round, mincost_runtime);

		// Print overall results
		if (!truth.empty())
			std::cout << "         cost of truth = " << getCosts(input, truth) << std::endl;
		std::cout << "cost of final solution = " << costs.back() << std::endl;
		std::cout << "     cheapest solution = " << mincost << " after " << mincost_runtime << " seconds" << std::endl;
	}

	std::cout << std::endl;
	
	// Finalize output
	ioutil::closeAllFiles();
	
	return totaltime-initialTime;
}
TEST_F(AirflowFixture, ForwardTranslator_DemoModel_2012)
{
  openstudio::path modelPath = (resourcesPath() / openstudio::toPath("contam") / openstudio::toPath("CONTAMTemplate.osm"));
  openstudio::osversion::VersionTranslator vt;
  boost::optional<openstudio::model::Model> optionalModel = vt.loadModel(modelPath);
  ASSERT_TRUE(optionalModel);
  openstudio::model::Model model = optionalModel.get();

  boost::optional<openstudio::model::Model> demoModel = buildDemoModel2012(model);

  // Write out the model
  openstudio::path outPath("CONTAMDemo2012.osm");
  EXPECT_TRUE(demoModel->save(outPath, true));

  ASSERT_TRUE(demoModel);

  openstudio::contam::ForwardTranslator translator;

  boost::optional<openstudio::contam::IndexModel> prjModel = translator.translateModel(demoModel.get());

  ASSERT_TRUE(prjModel);

  // 6 Zones
  EXPECT_EQ(6,prjModel->zones().size());
  int systemZoneCount=0;
  int interiorZoneCount=0;
  for(const openstudio::contam::Zone& zone : prjModel->zones()) {
    if(zone.system()) {
      systemZoneCount++;
    } else if(zone.variablePressure() && zone.variableContaminants()) {
      interiorZoneCount++;
    }
  }
  EXPECT_EQ(2,systemZoneCount);
  EXPECT_EQ(4,interiorZoneCount);
  // 26 Paths
  QVector<double> interiorMult, exteriorRoofMult, exteriorWallMult;
  interiorMult << 9 << 21 << 30;
  exteriorRoofMult << 30 << 70 << 136;
  exteriorWallMult << 9 << 21 << 24 << 30 << 51;
  EXPECT_EQ(26,prjModel->airflowPaths().size());
  int exhaustPathCount=0;
  int systemPathCount=0;
  int windPressurePathCount=0;
  int outsideAirPathCount=0;
  int recirculationPathCount=0;
  int plainPathCount=0;
  for(openstudio::contam::AirflowPath afp : prjModel->airflowPaths()) {
    if(afp.system()) {
      systemPathCount++;
    } else if(afp.windPressure()) {
      // This should be an exterior flow path
      if(afp.pe() == 5) {
        EXPECT_TRUE(exteriorWallMult.contains(afp.mult()));
      } else {
        EXPECT_TRUE(exteriorRoofMult.contains(afp.mult()));
      }
      windPressurePathCount++;
    } else if(afp.exhaust()) {
      exhaustPathCount++;
    } else if(afp.outsideAir()) {
      outsideAirPathCount++;
    } else if(afp.recirculation()) {
      recirculationPathCount++;
    } else {
      // This is an interior flow path
      EXPECT_TRUE(interiorMult.contains(afp.mult()));
      plainPathCount++;
    }
  }
  EXPECT_EQ(6,systemPathCount);
  EXPECT_EQ(12,windPressurePathCount);
  EXPECT_EQ(5,plainPathCount);
  EXPECT_EQ(1,recirculationPathCount);
  EXPECT_EQ(1,outsideAirPathCount);
  EXPECT_EQ(1,exhaustPathCount);

  // Check out the zones using the zone map
  QVector<std::string> zoneNames;
  zoneNames << "Library Zone" << "Office 1 Zone" << "Office 2 Zone" << "Hallway Zone";
  QMap<std::string,int> exteriorWallCount;
  exteriorWallCount["Library Zone"] = 4;
  exteriorWallCount["Office 1 Zone"] = 3;
  exteriorWallCount["Office 2 Zone"] = 3;
  exteriorWallCount["Hallway Zone"] = 2;

  std::map <openstudio::Handle, int> zoneMap = translator.zoneMap();
  EXPECT_EQ(4,zoneMap.size());

  std::vector<std::vector<int> > exteriorFlowPaths = prjModel->zoneExteriorFlowPaths();
  EXPECT_EQ(6,exteriorFlowPaths.size());

  for(const openstudio::model::ThermalZone& thermalZone : model.getConcreteModelObjects<openstudio::model::ThermalZone>()) {
    ASSERT_TRUE(zoneNames.contains(thermalZone.name().get()));
    unsigned zoneNumber = zoneMap[thermalZone.handle()];
    ASSERT_TRUE(zoneNumber > 0);
    ASSERT_TRUE(zoneNumber <= prjModel->zones().size());
    int zoneExteriorWallCount = exteriorFlowPaths[zoneNumber-1].size();
    EXPECT_EQ(exteriorWallCount[thermalZone.name().get()],zoneExteriorWallCount);
  }

  // Try setting some values to make sure things work
  EXPECT_TRUE(prjModel->setDef_T(297.15));
  EXPECT_TRUE(prjModel->setDef_T("297.15"));
  EXPECT_FALSE(prjModel->setDef_T("twoninetysevenpointonefive"));
  EXPECT_EQ(297.15,prjModel->def_T());
}
Ejemplo n.º 4
0
int wmain(int argc, Chr16** argv)
{
	Lock::setupGlobalLock();

	Error error;
	LogStdout log;
		
	class Fatal {};

	try
	{
		loginfo("Tomazos Resource Compiler 1.0 (c) Andrew Tomazos 2009");

		if (argc != 3)
		{
			error.what(L"Usage: ResourceCompiler <ResourceDir> <Out.cpp>");
			throw Fatal();
		}

		UTF16 sSourceDirPath = argv[1];
		UTF16 sOutPath = argv[2];

		Path sourceDir(error, sSourceDirPath);
		
		if (error)
			throw Fatal();

		UTF16 sFullSourceDirPath = UTF16(sourceDir);
		if (!sFullSourceDirPath.endsWith(L"\\"))
			sFullSourceDirPath = sFullSourceDirPath + L"\\";

		UTF16List fps;
		sourceDir.walk(ResourceCompilerWalker(fps));

		loginfo("Found %d files", fps.size());

		TreeMap<UTF16, Blob> data;

		{
			UTF16List::Iterator it(fps);
			UTF16 sFullFilePath;

			while (it(sFullFilePath))
			{
				if (!sFullFilePath.startsWith(sFullSourceDirPath))
				{
					Check();
					throw Fatal();
				}

				UTF16 sRelFilePath = sFullFilePath.suffix(sFullFilePath.length() - sFullSourceDirPath.length());

				Path file(error, sFullFilePath);
				
				if (error)
					throw Fatal();

				HInputStream fis;
				
				file.readFile(error, fis);

				if (error)
					throw Fatal();

				
				Blob sFileContent = fis->slurp(error);

				if (error)
					throw Fatal();

				loginfo("Found %s (%d bytes)", sRelFilePath.ptr(), sFileContent.length());

				data.add(sRelFilePath, sFileContent);
			}
		}

		Path outPath(error, sOutPath);

		if (error)
			throw Fatal();

		HOutputStream hOut;
		outPath.overwriteFile(error, hOut);

		if (error)
			throw Fatal();

		#define ResLine(x) { hOut->twrite(error, UTF8(x)); if (error) throw Fatal(); hOut->twrite(error, UTF8("\r\n")); if (error) throw Fatal(); }
		#define ResLineF(...) { ResLine(UTF8::format(__VA_ARGS__)); }

		ResLine("#include \"Runtime.h\"");
		ResLine("");
		ResLine("void ResourceManager::setup()");
		ResLine("{");

		{
			TreeMap<UTF16, Blob>::Iterator it(data);
			UTF16 sPath;
			Blob bData;
			int iCount = 0;

			int iNumResources = data.size();

			while (it(sPath, bData))
			{
				iCount++;
				UTF8 sId = UTF8::format("s_res_data_%d", iCount);
				
				ResLineF("    static UInt8 %s[] = { ", sId.ptr());
				for (int i = 0; i < bData.length(); i++)
				{
					if (i % 16 == 0)
					{
						hOut->twrite(error, UTF8("        "));
						if (error)
							throw Fatal();
					}

					hOut->twrite(error, UTF8::format("0x%.2X", UInt32(bData.idx<UInt8>(i))));

					if (error) throw Fatal();

					if (i != bData.length() - 1)
					{
						hOut->twrite(error, UTF8(", "));

						if (error)
							throw Fatal();
					}

					if (i % 16 == 15 || i == bData.length() - 1)
						ResLine("");
				}
				ResLineF("    };");
				ResLine("");
				ResLineF("    ResourceManager::instance()->set(%s, %s, %d);", stringToCStringLiteral(sPath).ptr(), sId.ptr(), bData.length());
				if (iCount != iNumResources)
					ResLine("");
			}
		}

		ResLine("}");

		#undef ResLine

		return 0;
	}
	catch (Fatal&)
	{
		if (error)
			logerr("%s", UTF16(error).ptr());
		
		return 1;
	}
}
Ejemplo n.º 5
0
bool ZipFile::extractCurrentFile(const std::string& path, bool whiny)
{    
    int ret;
    unz_file_info info;
    char fname[1024];

    try {
        internal::api("unzGetCurrentFileInfo", unzGetCurrentFileInfo(this->fp, &info, fname, 1024, nullptr, 0, nullptr, 0));
        
        std::string outPath(path);
        fs::addnode(outPath, fname);

        TraceL << "Extracting asset: " << outPath << endl;

        // Create directory
#if !WIN32
        const int FILE_ATTRIBUTE_DIRECTORY = 0x10;
#endif
        if (info.external_fa & FILE_ATTRIBUTE_DIRECTORY || 
            fname[strlen(fname) - 1] == fs::delimiter) {
            TraceL << "Create directory: " << outPath << endl;
            fs::mkdirr(outPath);
        }

        // Create file
        else {            
            TraceL << "Create file: " << outPath << endl;

            // Note: If this fails the file we are trying 
            // to write may be in use on the filesystem.
            openCurrentFile();

            std::ofstream ofs(outPath, std::ios::binary | std::ios::out);

            // FIX: FILE_ATTRIBUTE_DIRECTORY can be inconsistent, so we 
            // need to be ready to create directories if the output file 
            // fails to open.
            if (!ofs.is_open()) {
                fs::mkdirr(fs::dirname(outPath));
                ofs.open(outPath);
            }

            if (!ofs.is_open())
                throw std::runtime_error("Cannot open zip output file: " + outPath);
            
            char buffer[16384];
            while ((ret = unzReadCurrentFile(this->fp, buffer, 16384)) > 0)
                ofs.write(buffer, ret);
            
            ofs.close();
            
            internal::api("unzReadCurrentFile", ret); // throw file read errors
            closeCurrentFile();
        }
    } 
    catch (std::exception& exc) {
        ErrorL << "Cannot unzip file: " << exc.what() << endl;
        if (whiny)
            throw exc;
        return false;
    }
    return true;
}
Ejemplo n.º 6
0
int main( int argc, char **argv )
{
    std::cout << "Skype History Exporter v1.3.0 Stable\n"
              << "   WEBSITE: [ https://github.com/Temptin/SkypeExport ]\n"; // helps people find updated versions

    // prepare command line parameters
    po::options_description desc( "Available options" );
    desc.add_options()
    ( "help,h", "show this help message" )
    ( "db,i", po::value<std::string>()->default_value("./main.db"), "path to your Skype profile's main.db" )
    ( "outpath,o", po::value<std::string>()->default_value("./ExportedHistory"), "path where all html files will be written; will be created if missing" )
    ( "contacts,c", po::value<std::string>(), "space-separated list of the SkypeIDs to output; defaults to blank which outputs all contacts" )
    ( "timefmt,t", po::value<std::string>()->default_value("12h"), "format of timestamps in history output; set to \"12h\" for 12-hour clock (default), \"24h\" for a 24-hour clock, \"utc12h\" for UTC-based 12-hour clock, or \"utc24h\" for UTC-based 24-hour clock" )
    ;

    // parse and verify command line parameters
    po::variables_map vm;
    try {
        po::store( po::parse_command_line( argc, argv, desc ), vm );
        po::notify( vm );
    } catch(...) { // malformatted input of some kind, so just show the user the help and exit the program
        std::cout << "\nError: Invalid parameters!\n\n" << desc << "\n";
        return 1;
    }

    // show the help and exit if that's what they asked for
    if( vm.count( "help" ) ) {
        std::cout << "\n" << desc << "\n";
        return 0;
    }

    // detect their desired time format (24 hour or 12 hour time; default to 12h) and time reference (UTC or local time; default to local)
    uint8_t timeFormat = ( vm["timefmt"].as<std::string>() == "24h" || vm["timefmt"].as<std::string>() == "utc24h" ? 2 : 1 ); // used for formatTime() input, where 2=24h, 1=12h
    int8_t timeReference = ( vm["timefmt"].as<std::string>() == "utc12h" || vm["timefmt"].as<std::string>() == "utc24h" ? 0 : 1 ); // 0=utc, 1=local

    // verify the provided database and output paths and turn them into boost filesystem objects, then create the output path if needed
    fs::path dbPath( vm["db"].as<std::string>() );
    fs::path outPath( vm["outpath"].as<std::string>() );
    dbPath.make_preferred(); // formats all slashes according to operating system
    outPath.make_preferred();
    try {
        if( !fs::exists( dbPath ) || !fs::is_regular_file( dbPath ) ) {
            std::cout << "\nError: Database " << dbPath.leaf() << " does not exist at the provided path!\n\n" << desc << "\n";
            return 1;
        }
        if( fs::file_size( dbPath ) == 0 ) {
            std::cout << "\nError: Database " << dbPath.leaf() << " is empty!\n\n" << desc << "\n";
            return 1;
        }
        if( fs::exists( outPath ) && !fs::is_directory( outPath ) ) {
            std::cout << "\nError: Output path " << outPath << " already exists and is not a directory!\n\n" << desc << "\n";
            return 1;
        } else if( !fs::exists( outPath ) ) {
            // outPath either exists and is a directory, or doesn't exist.
            // we must now create the path if missing. will throw an exception on errors such as lack of write permissions.
            fs::create_directories( outPath ); // creates any missing directories in the given path.
        }
    } catch( const fs::filesystem_error &ex ) {
        std::cout << "\nError: " << ex.what() << "\n";
        return 1;
    }

    // if they've provided a space-separated list of contacts to output, we need to tokenize it and store the SkypeIDs
    std::map<std::string,bool> outputContacts; // filled with all contacts to output, or blank to output all
    std::map<std::string,bool>::iterator outputContacts_it;
    if( vm.count( "contacts" ) ) {
        boost::char_separator<char> sep( " " );
        boost::tokenizer< boost::char_separator<char> > tokens( vm["contacts"].as<std::string>(), sep );
        for( boost::tokenizer< boost::char_separator<char> >::iterator identities_it( tokens.begin() ); identities_it != tokens.end(); ++identities_it ) {
            outputContacts_it = outputContacts.find( (*identities_it) );
            if( outputContacts_it == outputContacts.end() ) { // makes sure we only add each unique skypeID once, even if the idiot user has provided it multiple times
                outputContacts.insert( std::pair<std::string,bool>( (*identities_it), false ) ); // NOTE: we initialize the skypeID as false, and will set it to true if it's been output
            }
        }
    }

    // alright, let's begin output...
    try {
        // open Skype history database
        SkypeParser::CSkypeParser sp( dbPath.string() );

        // display all options (input database, output path, and all names to output (if specified))
        std::cout << "  DATABASE: [ " << dbPath << " ]\n" // note: no newline prefix (aligns it perfectly with version header)
                  << "   TIMEFMT: [ \"" << ( timeFormat == 1 ? "12h" : "24h" ) << " " << ( timeReference == 0 ? "UTC" : "Local Time" ) << "\" ]\n"
                  << "    OUTPUT: [ " << outPath << " ]\n";
        if( outputContacts.size() > 0 ) {
            std::cout << "  CONTACTS: [ \"";
            for( std::map<std::string,bool>::const_iterator it( outputContacts.begin() ); it != outputContacts.end(); ++it ) {
                std::cout << (*it).first;
                if( boost::next( it ) != outputContacts.end() ) {
                    std::cout << "\", \"";    // appended after every element except the last one
                }
            }
            std::cout << "\" ]\n\n";
        } else {
            std::cout << "  CONTACTS: [ \"*\" ]\n\n";
        }

        // grab a list of all contacts encountered in the database
        const SkypeParser::skypeIDs_t &users = sp.getSkypeUsers();

        // output statistics
        std::cout << "Found " << users.size() << " contacts in the database...\n\n";

        // output contacts, skipping some in case the user provided a list of contacts to export
        for( SkypeParser::skypeIDs_t::const_iterator it( users.begin() ); it != users.end(); ++it ) {
            const std::string &skypeID = (*it);

            // skip if we're told to filter contacts
            outputContacts_it = outputContacts.find( (*it) ); // store iterator here since we'll set it to true after outputting, if contact filters are enabled
            if( outputContacts.size() > 0 && ( outputContacts_it == outputContacts.end() ) ) {
                continue;    // if no filters, it's always false; if filters it's true if the contact is to be skipped
            }

            // construct the final path to the log file for this user
            fs::path logPath( outPath );
            logPath /= ( (*it) + ".skypelog.htm" ); // appends the log filename and chooses the appropriate path separator

            // output exporting header
            std::cout << " * Exporting: " << skypeID << " (" << sp.getDisplayNameAtTime( skypeID, -1 ) << ")\n";
            std::cout << "   => " << logPath << "\n";
            sp.exportUserHistory( skypeID, logPath.string(), timeFormat, timeReference );
            if( outputContacts.size() > 0 ) {
                (*outputContacts_it).second = true;    // since filters are enabled and we've come here, we know we've output the person as requested, so mark them as such
            }
        }
    } catch( const std::exception &e ) {
        std::cout << "Error while processing Skype database: \"" << e.what() << "\".\n";
        return 1;
    }

    // check for any missing IDs if filtered output was requested
    for( std::map<std::string,bool>::const_iterator it( outputContacts.begin() ); it != outputContacts.end(); ++it ) {
        if( (*it).second == false ) { // a requested ID that was not found in the database
            std::cout << " * Not Found: " << (*it).first << "\n";
        }
    }

    std::cout << "\nExport finished.\n";

    return 0;
}
Ejemplo n.º 7
0
int main (int argc, char** argv)
{
  pcl::PointCloud<pcl::PointXYZ> cloud;

	int width, height;
	int nPoints;
	float *pointsX, *pointsY, *pointsZ;
	float px, py, pz;

	if(argc < 2){
		std::cerr << "# args: infile.dat, outpath" << std::endl;
		return EXIT_FAILURE;
	}

	std::string outpathInput = argv[2];


	fprintf(stderr, "# reading data from file: %s\n", argv[1]);

	FILE *fptr = fopen(argv[1], "r");
	if(fptr == NULL){
		fprintf(stderr, "# bad input file: %s\n", argv[1]);
		return EXIT_FAILURE;
	}
	
	fread(&nPoints, sizeof(int), 1, fptr);
	fread(&height, sizeof(int), 1, fptr);
	fread(&width, sizeof(int), 1, fptr);

	fprintf(stderr, "# npoints %d\n", nPoints );  	
	fprintf(stderr, "# width: %d height: %d\n", width, height );  
		
	pointsX = (float*)malloc(sizeof(float)*nPoints);
	pointsY = (float*)malloc(sizeof(float)*nPoints);
	pointsZ = (float*)malloc(sizeof(float)*nPoints);
	
	for(int i = 0; i < nPoints; i++){
		fread(&px, sizeof(float), 1, fptr);
		fread(&py, sizeof(float), 1, fptr);
		fread(&pz, sizeof(float), 1, fptr);
		pointsX[i] = px;
		pointsY[i] = py;
		pointsZ[i] = pz;
	}
	
	fclose(fptr);

	int nclouds = 4;
	int offset = 0;
	int cloudSize = nPoints/nclouds;
	std::stringstream ss;

	for(int index = 0; index < nclouds; ++index){
		// Fill in the cloud data
		// we know this from the pfm file
		offset = index*cloudSize;
		cloud.width    = cloudSize;
		cloud.height   = 1;
		cloud.is_dense = false;
		cloud.points.resize (cloud.width * cloud.height);
		for (size_t i = 0; i < cloud.points.size (); ++i)
			{
				cloud.points[i].x = pointsX[i+offset];
				cloud.points[i].y = pointsY[i+offset];
				cloud.points[i].z = pointsZ[i+offset];
			}


		ss << "cloud_cam_" << index << ".pcd";
		boost::filesystem::path outPath(outpathInput); // append the result string to the outpath correctly
		outPath /= ss.str();
		pcl::io::savePCDFileASCII (outPath.native(), cloud);

		std::cerr << "Saved " << cloud.points.size () << " data points to: " << outPath.native() << std::endl;
		ss.clear(); // reset the stringstream
		ss.str("");
		
	}

	// and write out the whole thing too
	cloudSize = nPoints;
	cloud.width    = cloudSize;
	cloud.height   = 1;
	cloud.is_dense = false;
	cloud.points.resize (cloud.width * cloud.height);
	for (size_t i = 0; i < cloud.points.size (); ++i)
		{
			cloud.points[i].x = pointsX[i];
			cloud.points[i].y = pointsY[i];
			cloud.points[i].z = pointsZ[i];
		}

	ss << "cloud_full.pcd";
	boost::filesystem::path outPath(outpathInput); // append the result string to the outpath correctly
	outPath /= ss.str();
	#ifdef PCDWRITEBINFILE
	pcl::io::savePCDFileBinary (outPath.native(), cloud);
	#else 
	pcl::io::savePCDFileASCII (outPath.native(), cloud);
	#endif

	std::cerr << "Saved " << cloud.points.size () << " data points to: " << outPath.native() << std::endl;
	ss.clear(); // reset the stringstream
	ss.str("");

	free(pointsX);
	free(pointsY);
	free(pointsZ);

  return (0);
}
Ejemplo n.º 8
0
int main (int argc, char** argv){
	
	if(argc < 3) {
		std::cerr << "# computes transform to rotate a generic cube to a clustered cube " << std::endl;
		std::cerr << "# run with <inputcube..path> <outpath> <id>" << std::endl;
		return EXIT_FAILURE;
	}
	
	std::string filepath = std::string(argv[1]); 
	std::string outpath = std::string(argv[2]); 
	int id = atoi(argv[3]);
	std::cerr << "# processing: " << filepath << std::endl;
	std::cerr << "# outpath: " << outpath << std::endl;
	std::cerr << "# id: " << id << std::endl;

	//pcl::PointCloud<pcl::PointXYZ>::Ptr cloud = readBinfileCCS(filepath);
	pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
	pcl::PointCloud<pcl::PointXYZ>::Ptr cubeCloud;
	pcl::PointCloud<pcl::PointXYZ>::Ptr Final (new pcl::PointCloud<pcl::PointXYZ>);

	pcl::io::loadPCDFile(filepath, *cloud);

	std::cerr << "# read width: " << cloud->width;
	std::cerr << " height: " << cloud->height << std::endl;

	#ifdef DEBUG
	std::cerr << "# generating cubeCloud" << std::endl;
	#endif
	// low res
	cubeCloud = genTestCube(nShortSideLowRes,nLongSideLowRes); // gen our comparison cube
	// higher res
	//cubeCloud = genTestCube(nShortSideHighRes,nLongSideHighRes); // gen our comparison cube

	#ifdef DEBUG
	std::cerr << "# starting icp" << std::endl;
	#endif
	pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;
  icp.setInputCloud(cubeCloud);
  icp.setInputTarget(cloud);
	icp.setTransformationEpsilon(1e-6);
	icp.setMaximumIterations(128);
	icp.setRANSACOutlierRejectionThreshold(0.01);
	//icp.setMaxCorrespondenceDistance(0.01);

  icp.align(*Final);

#ifdef DEBUG
  std::cout << "has converged:" << icp.hasConverged() << " score: " <<
  icp.getFitnessScore() << std::endl;
  std::cout << icp.getFinalTransformation() << std::endl;
#endif

	std::stringstream ss;
	
	ss << "fitted_cube_" << id << ".pcd";
	boost::filesystem::path outPath(outpath); // append the result string to the outpath correctly
	outPath /= ss.str();
	std::cerr << "# filename: " << outPath << std::endl;
	//writeBinfileCCS(Final, outpath);
	pcl::io::savePCDFileASCII (outPath.native(), *Final);

	std::ofstream file;
	ss.clear();
	ss.str("");
	ss << "transformation_" << id << ".txt";
	outPath.clear();
	outPath /= outpath;
	outPath /= ss.str();
	std::cerr << "# filename: " << outPath << std::endl;
	file.open(outPath.c_str());
	file << icp.getFinalTransformation() << std::endl;
	file.close();

	// append to the centroids file 
	ss.clear();
	ss.str("");
	ss << "centroids_icp.dat";
	outPath.clear();
	outPath /= outpath; 
	outPath /= ss.str();
	file.open(outPath.c_str(), std::ios::app | std::ios::out);

	// get the transmat
	Eigen::Matrix4f transMat = icp.getFinalTransformation();
	
	// write out the id, 
	file << id; 
	// the centroid (first 3 elts of final col)
	file << transMat(0, 3) << " " << transMat(1, 3) << " " << transMat(2,3);
	// the y rotation which should be (1,1) ? 
	file << transMat(1,1) << std::endl;

	file.close();

	return EXIT_SUCCESS;
}