int main(int argc, char** argv) {
  size_t parent_pid = getppid();
  // Options
  std::string program_name = argv[0];
  std::string server_address;

  // Handle server commandline options
  boost::program_options::variables_map vm;
  po::options_description desc("Allowed options");
  desc.add_options()
      ("help", "Print this help message.")
      ("server_address", 
       po::value<std::string>(&server_address)->implicit_value(server_address),
       "This must be a valid ZeroMQ endpoint and "
                         "is the address the server listens on");

  po::positional_options_description positional;
  positional.add("server_address", 1);

  // try to parse the command line options
  try {
    po::command_line_parser parser(argc, argv);
    parser.options(desc);
    parser.positional(positional);
    po::parsed_options parsed = parser.run();
    po::store(parsed, vm);
    po::notify(vm);
  } catch(std::exception& error) {
    std::cout << "Invalid syntax:\n"
              << "\t" << error.what()
              << "\n\n" << std::endl
              << "Description:"
              << std::endl;
    print_help(program_name, desc);
    return 1;
  }

  if(vm.count("help")) {
    print_help(program_name, desc);
    return 0;
  }

  try {
    graphlab::lambda::init_python(argc, argv);
  } catch (const std::string& error) {
    logstream(LOG_WARNING) << "Fail initializing python: " << error << std::endl;
    exit(-1);
  }

  // construct the server
  cppipc::comm_server server(std::vector<std::string>(), "", server_address);

  server.register_type<graphlab::lambda::lambda_evaluator_interface>([](){
                                            return new graphlab::lambda::pylambda_evaluator();
                                          });
  server.register_type<graphlab::lambda::graph_lambda_evaluator_interface>([](){
                                            return new graphlab::lambda::graph_pylambda_evaluator();
                                          });

  server.start();

#ifdef HAS_TCMALLOC
  graphlab::thread memory_release_thread;
  memory_release_thread.launch(memory_release_loop);
#endif

  while(1) {
    sleep(5);
    // has parent_pid and parent_pid 
    if (parent_pid != 0 && kill(parent_pid, 0) == -1) {
      break;
    }

  }

#ifdef HAS_TCMALLOC
  stop_memory_release_thread = true;
  memory_release_cond.signal();
  memory_release_thread.join();
#endif

}
Exemple #2
0
    threads::thread_state_ex_enum suspend(
        util::steady_time_point const& abs_time,
        util::thread_description const& description, error_code& ec)
    {
        // schedule a thread waking us up at_time
        threads::thread_self& self = threads::get_self();
        threads::thread_id_type id = threads::get_self_id();

        // handle interruption, if needed
        threads::interruption_point(id, ec);
        if (ec) return threads::wait_unknown;

        // let the thread manager do other things while waiting
        threads::thread_state_ex_enum statex = threads::wait_unknown;

        {
#ifdef HPX_HAVE_VERIFY_LOCKS
            // verify that there are no more registered locks for this OS-thread
            util::verify_no_locks();
#endif
#ifdef HPX_HAVE_THREAD_DESCRIPTION
            detail::reset_lco_description desc(id, description, ec);
#endif
#ifdef HPX_HAVE_THREAD_BACKTRACE_ON_SUSPENSION
            detail::reset_backtrace bt(id, ec);
#endif
            threads::thread_id_type timer_id = threads::set_thread_state(id,
                abs_time, threads::pending, threads::wait_timeout,
                threads::thread_priority_boost, ec);
            if (ec) return threads::wait_unknown;

            // suspend the HPX-thread
            statex = self.yield(threads::suspended);

            if (statex != threads::wait_timeout)
            {
                error_code ec(lightweight);    // do not throw
                threads::set_thread_state(timer_id,
                    threads::pending, threads::wait_abort,
                    threads::thread_priority_boost, ec);
            }
        }

        // handle interruption, if needed
        threads::interruption_point(id, ec);
        if (ec) return threads::wait_unknown;

        // handle interrupt and abort
        if (statex == threads::wait_abort) {
            std::ostringstream strm;
            strm << "thread(" << threads::get_self_id() << ", "
                  << threads::get_thread_description(id)
                  << ") aborted (yield returned wait_abort)";
            HPX_THROWS_IF(ec, yield_aborted, "suspend_at",
                strm.str());
        }

        if (&ec != &throws)
            ec = make_success_code();

        return statex;
    }
Exemple #3
0
void
TextureHostShmemD3D11::UpdateImpl(const SurfaceDescriptor& aImage, nsIntRegion *aRegion)
{
  MOZ_ASSERT(aImage.type() == SurfaceDescriptor::TShmem);

  AutoOpenSurface openSurf(OPEN_READ_ONLY, aImage);

  nsRefPtr<gfxImageSurface> surf = openSurf.GetAsImage();

  gfxIntSize size = surf->GetSize();

  uint32_t bpp = 0;

  DXGI_FORMAT dxgiFormat;
  switch (surf->Format()) {
  case gfxImageSurface::ImageFormatRGB24:
    mFormat = FORMAT_B8G8R8X8;
    dxgiFormat = DXGI_FORMAT_B8G8R8A8_UNORM;
    bpp = 4;
    break;
  case gfxImageSurface::ImageFormatARGB32:
    mFormat = FORMAT_B8G8R8A8;
    dxgiFormat = DXGI_FORMAT_B8G8R8A8_UNORM;
    bpp = 4;
    break;
  case gfxImageSurface::ImageFormatA8:
    mFormat = FORMAT_A8;
    dxgiFormat = DXGI_FORMAT_A8_UNORM;
    bpp = 1;
    break;
  }

  mSize = IntSize(size.width, size.height);

  CD3D11_TEXTURE2D_DESC desc(dxgiFormat, size.width, size.height,
                            1, 1, D3D11_BIND_SHADER_RESOURCE, D3D11_USAGE_IMMUTABLE);

  int32_t maxSize = GetMaxTextureSizeForFeatureLevel(mDevice->GetFeatureLevel());
  if (size.width <= maxSize && size.height <= maxSize) {
    D3D11_SUBRESOURCE_DATA initData;
    initData.pSysMem = surf->Data();
    initData.SysMemPitch = surf->Stride();

    mDevice->CreateTexture2D(&desc, &initData, byRef(mTextures[0]));
    mIsTiled = false;
  } else {
    mIsTiled = true;
    uint32_t tileCount = GetRequiredTiles(size.width, maxSize) *
                          GetRequiredTiles(size.height, maxSize);

    mTileTextures.resize(tileCount);

    for (uint32_t i = 0; i < tileCount; i++) {
      IntRect tileRect = GetTileRect(i);

      desc.Width = tileRect.width;
      desc.Height = tileRect.height;

      D3D11_SUBRESOURCE_DATA initData;
      initData.pSysMem = surf->Data() + tileRect.y * surf->Stride() + tileRect.x * bpp;
      initData.SysMemPitch = surf->Stride();

      mDevice->CreateTexture2D(&desc, &initData, byRef(mTileTextures[i]));
    }
  }
}
Exemple #4
0
int main(int argc, char* argv[]) {
    try {
        po::options_description desc( "Options" );
        desc.add_options()
            ( "help,h", "Show detailed help." )
			( "options,p", "Show parameter information." )
			( "version,p", "Show version information." )
			( "input-file,i", po::value<std::vector<std::string> >(), "Define file(s) for the convertion input." )
			( "input-type,I", po::value<std::vector<std::string> >(), "Define file type(s) for automatic conversion of files in the working directory." )
			( "output-file,o", po::value<std::string>(), "Define file for the convertion output." )
			( "noheader,h", "Disable adding of header support defines." )
            ( "const,C", "Define array as const." )
			( "respectcase,r", "Disable converting file types into lower case." )
			( "wxnone,w", "Disable adding of wxWidgets support macro's." )
			( "wxheader,W", po::value<std::string>()->default_value( "wx/wx.h" ), "Select the header that includes wxWidgets (precompiled header?)." )
			( "appendtype,t", "Add the file type at the end of the identifier (myimage_png)." )
			( "text,T", "Disable binary output and use text output, converts feed codes to systems defaults." )
          ( "silent", "No console output except errors")
		;

        po::positional_options_description posdesc;
        posdesc.add( "input-file", -1 );

        po::variables_map opt;
        po::store( po::command_line_parser( argc, argv ).options( desc ).positional( posdesc ).run(), opt );
//		po::store( po::parse_config_file( fs::ifstream( fs::path( "default.cfg" ) ), desc ), opt );
        po::notify( opt );

//		std::cout << WXINCLUDE_INFO << std::endl;

		/* Show options when requested */
        if ( opt.count( "options" ) ) {
			std::cout << desc << std::endl << std::endl;
            exit( 0 );
        }

		/* Show help when requested */
        if ( opt.count( "help" ) ) {
			std::cout << WXINCLUDE_HELP;
			std::cout << std::endl << desc << std::endl << std::endl;
            exit( 0 );
        }

		/* Show version when requested */
        if ( opt.count( "version" ) ) {
			std::cout << WXINCLUDE_VERSION << std::endl;
            exit( 0 );
        }

        bool silent = opt.count( "silent" );

		/* Process */
        if ( opt.count( "input-file" ) || opt.count( "input-type" ) ) {
			if ( opt.count( "output-file" ) ) {	
				/* Create timer */
				boost::timer timer;

				/* Create output file */
				std::string headername( opt[ "output-file" ].as<std::string>() );

				fs::path outputpath( headername );
				fs::ofstream output( outputpath, std::ios::out | std::ios::trunc );

				/* Use buffer */
				char outbuffer[BUFFER_SIZE];
				output.rdbuf()->pubsetbuf( outbuffer, BUFFER_SIZE );

//				if ( !opt.count( "text" ) )
//					output.setf( std::ios::binary );

				if ( !output )
					throw std::runtime_error( "Failed to create output file!" );

				/* Show status */
                if (!silent)
                  std::cout << "Build  : file '" << outputpath.leaf() << "'..." << std::endl;

				/* Get base name of file */
				headername = fs::basename( outputpath );

				/* Data string stream */
				std::ostringstream data;

				/* Write header start when wanted */
				if ( !opt.count( "noheader" ) )
					defineheader_start( data, headername, opt.count( "wxnone" ) ? false : true, opt.count( "const" ) ? true : false );

				/* Get defined or else default wx header */
				std::string includename( opt[ "wxheader" ].as<std::string>() );

				/* Write macros when wanted */
				if ( !opt.count( "wxnone" ) )
					definemacros( data, includename, opt[ "wxheader" ].defaulted() );

				/* Common input buffer */
				char inbuffer[BUFFER_SIZE];

				/* Process input files based on provided list */
				if ( opt.count( "input-file" ) ) {
					std::vector<std::string> files( opt[ "input-file" ].as<std::vector<std::string> >() );

					BOOST_FOREACH( std::string& file, files ) {
						fs::path inputpath( file );
						std::string fileext( fs::extension( inputpath ) );

						fs::ifstream input( inputpath, std::ios::in | std::ios::binary | std::ios::ate );
						input.rdbuf()->pubsetbuf( inbuffer, BUFFER_SIZE ); 

						if ( input.is_open() ) {
							/* Show status */
                          if (!silent)
							std::cout << "Process: file '" << file << "'..." << std::endl;

							/* Remove extension */
                            file = inputpath.filename().string();
							boost::erase_last( file, fileext );

							if ( !opt.count( "respectcase" ) )
								boost::to_lower( fileext );

							/* Append type */
							if ( opt.count( "appendtype" ) ) {
								boost::erase_first( fileext, "." );

								/* Static and NO copy constructor for speed */
								static boost::format fmt( "%1%_%2%" );
								file = boost::str( fmt % file % fileext );
							}

							/* Lower case names when wanted */
							if ( !opt.count( "respectcase" ) )
								boost::to_lower( file );

							/* Process file */
							definefile( data, input, file, opt.count( "const" ) ? true : false );
						} else {
							/* Only show warning, other files need to be processed */
							std::cout << "Warning: input file '" << file << "' failed to open." << std::endl;
						}
					}
				}

				/* Process input files based on provided type */
				if ( opt.count( "input-type" ) ) {
					std::vector<std::string> types( opt[ "input-type" ].as<std::vector<std::string> >() );

					for ( fs::directory_iterator dir_itr( fs::initial_path() ); dir_itr != fs::directory_iterator(); ++dir_itr ) {
						BOOST_FOREACH( std::string& type, types ) {
							/* Normal file? */
							if ( fs::is_regular( dir_itr->status() ) ) {
								/* Wanted type? */
								std::string fileext( fs::extension( dir_itr->path() ));

								bool equals = false;

								if ( opt.count( "respectcase" ) )
									equals = boost::equals( fileext, type );
								else
									equals = boost::iequals( fileext, type );

								if ( equals ) {
									fs::ifstream input( dir_itr->path(), std::ios::in | std::ios::binary | std::ios::ate );
									input.rdbuf()->pubsetbuf( inbuffer, BUFFER_SIZE ); 

									std::string file( dir_itr->path().filename().string() );

									if ( input.is_open() ) {
										/* Show status */
                                      if (!silent)
										std::cout << "Process: file '" << file << "'..." << std::endl;

										/* Remove extension */
										boost::erase_last( file, fileext );

										/* Append type */
										if ( opt.count( "appendtype" ) ) {
											boost::erase_first( fileext, "." );

											/* Static and NO copy constructor for speed */
											static boost::format fmt( "%1%_%2%" );
											file = boost::str( fmt % file % fileext );
										}

										/* Lower case names when wanted */
										if ( !opt.count( "respectcase" ) )
											boost::to_lower( file );

										/* Process file */
										definefile( data, input, file, opt.count( "const" ) ? true : false );
									} else {
										/* Only show warning, other files need to be processed */
										std::cout << "Warning: input file '" << file << "' failed to open." << std::endl;
									}
								}
							}
						}
					}
				}
void PreprocessTransferFreenect(libusb_transfer* transfer, const int read)
{
	fnusb_isoc_stream* xferstrm = (fnusb_isoc_stream*)transfer->user_data;
	freenect_device* dev = xferstrm->parent->parent;
	packet_stream* pktstrm = (transfer->endpoint == 0x81) ? &dev->video : &dev->depth;

	// Kinect Camera Frame Packed Header:
	struct pkt_hdr
	{
		uint8_t magic[2];
		uint8_t pad;
		uint8_t flag;
		uint8_t unk1;
		uint8_t seq;
		uint8_t unk2;
		uint8_t unk3;
		uint32_t timestamp;
	};  // 12 bytes

	//packet sizes:
	//          first  middle  last
	// Bayer    1920    1920    24
	// IR       1920    1920  1180
	// YUV422   1920    1920    36
	// Depth    1760    1760  1144
	const unsigned int pktlen = sizeof(pkt_hdr) + pktstrm->pkt_size;
	const unsigned int pktend = sizeof(pkt_hdr) + pktstrm->last_pkt_size;

	unsigned int remaining (read);
	unsigned int leftover (transfer->length);
	unsigned char* pktbuffer (transfer->buffer);
	const int pkts (transfer->num_iso_packets);
	for (int i=0; i<pkts; ++i)
	{
		const pkt_hdr& header (*(pkt_hdr*)pktbuffer);
		libusb_iso_packet_descriptor& desc (transfer->iso_packet_desc[i]);
		if ((header.magic[0] == 'R') && (header.magic[1] == 'B'))
		{
			switch(header.flag & 0x0F)
			{
			case 0x01 : // begin
			case 0x02 : // middle
				desc.actual_length = __min(remaining, pktlen);
				break;
			case 0x05 : // final
				desc.actual_length = __min(remaining, pktend);
				break;
			default :
				fprintf(stdout, "0x%02X\n", header.flag);
				break;
			}
		}
		else
		{
			desc.actual_length = 0;
		}
		remaining -= desc.actual_length;
		pktbuffer += desc.length;   // a.k.a: += 1920
		leftover  -= desc.length;   // a.k.a: -= 1920
	}

	if (remaining > 0)
	{
		fprintf(stdout, "%d remaining out of %d\n", remaining, read);
		if (remaining == read)
		{
		}
	}
}
Exemple #6
0
int main(int argc, char** argv)
{
	/* ARG PARSER *****************************************************/
	std::string fn_rules;
	std::string fn_bary;
	std::string fn_dev;
	std::string fn_out;

	boostPO::variables_map vm;
	boostPO::options_description desc("Allowed options");
	desc.add_options()
		("help,h",
		 "produce help message")
		("rule,r",
		 boostPO::value<std::string>(&fn_rules)->required(),
		 "REQUIRED | Subdivision rule filename")
		("bary,b",
		 boostPO::value<std::string>(&fn_bary),
		 "Barycenter offset filename (for each rule id)")
		("dev,d",
		 boostPO::value<std::string>(&fn_dev),
		 "Offset filename (for each structural indices)")
		("out,o",
		 boostPO::value<std::string>(&fn_out),
		 "Output filename")
		;

	try
	{
		boostPO::store(
				boostPO::command_line_parser(argc, argv).
				options(desc).run(), vm);
		boostPO::notify(vm);
	}
	catch(boost::program_options::error& e)
	{
		std::cerr << e.what() << std::endl;
		std::cout << desc << "\n";
		exit(EXIT_FAILURE);
	}

	if(vm.count("help"))
	{
		std::cout << desc << "\n";
		exit(EXIT_SUCCESS);
	}

	/* PROG ***********************************************************/
	Sampler sampler(fn_rules, fn_bary, fn_dev);
	/*
	WriterFilePts write(fn_out);
	/*/
	WriterEmpty write;
	//*/
	char ans;
	float density = 2;
	unsigned short int seed = 0;
	float spaceScale = 0.21;
	while(true)
	{
		std::cout << "=================================" << std::endl;
		std::cout << "? Generate a distribution (Y/n) ? ";
		if( std::cin.peek() == '\n' ) ans='y';
		else if( !(std::cin >> ans) ) break;
		std::cin.ignore();
		if( std::cin.fail() || ans=='n' || ans=='N') break;

		std::cout << "? set initial seed [0-" << sampler.tiling().ruleSize()-1 << "] (" << ++seed << "): ";
		if( std::cin.peek() == '\n' );
		else if( !(std::cin >> seed) ) break;
		std::cin.ignore();

		std::cout << "? set final density [0-inf] (" << density << "): ";
		if( std::cin.peek() == '\n' );
		else if( !(std::cin >> density) ) break;
		std::cin.ignore();

		std::cout << "? set boundary (" << spaceScale << "): ";
		if( std::cin.peek() == '\n' );
		else if( !(std::cin >> spaceScale) ) break;
		std::cin.ignore();

		sampler.generateUniform(density, -1, write, seed, spaceScale);
	}
}
Exemple #7
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args, file, ant, subdev, ref;
    size_t total_num_samps;
    double rate, freq, gain, bw;
    std::string addr, port;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "multi uhd device address args")
        ("nsamps", po::value<size_t>(&total_num_samps)->default_value(1000), "total number of samples to receive")
        ("rate", po::value<double>(&rate)->default_value(100e6/16), "rate of incoming samples")
        ("freq", po::value<double>(&freq)->default_value(0), "rf center frequency in Hz")
        ("gain", po::value<double>(&gain)->default_value(0), "gain for the RF chain")
        ("ant", po::value<std::string>(&ant), "antenna selection")
        ("subdev", po::value<std::string>(&subdev), "subdevice specification")
        ("bw", po::value<double>(&bw), "analog frontend filter bandwidth in Hz")
        ("port", po::value<std::string>(&port)->default_value("7124"), "server udp port")
        ("addr", po::value<std::string>(&addr)->default_value("192.168.1.10"), "resolvable server address")
        ("ref", po::value<std::string>(&ref)->default_value("internal"), "reference source (internal, external, mimo)")
        ("int-n", "tune USRP with integer-N tuning")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help")){
        std::cout << boost::format("UHD RX to UDP %s") % desc << std::endl;
        return ~0;
    }

    //create a usrp device
    std::cout << std::endl;
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

    //Lock mboard clocks
    usrp->set_clock_source(ref);

    //set the rx sample rate
    std::cout << boost::format("Setting RX Rate: %f Msps...") % (rate/1e6) << std::endl;
    usrp->set_rx_rate(rate);
    std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate()/1e6) << std::endl << std::endl;

    //set the rx center frequency
    std::cout << boost::format("Setting RX Freq: %f MHz...") % (freq/1e6) << std::endl;
    uhd::tune_request_t tune_request(freq);
    if(vm.count("int-n")) tune_request.args = uhd::device_addr_t("mode_n=integer");
    usrp->set_rx_freq(tune_request);
    std::cout << boost::format("Actual RX Freq: %f MHz...") % (usrp->get_rx_freq()/1e6) << std::endl << std::endl;

    //set the rx rf gain
    std::cout << boost::format("Setting RX Gain: %f dB...") % gain << std::endl;
    usrp->set_rx_gain(gain);
    std::cout << boost::format("Actual RX Gain: %f dB...") % usrp->get_rx_gain() << std::endl << std::endl;

    //set the analog frontend filter bandwidth
    if (vm.count("bw")){
        std::cout << boost::format("Setting RX Bandwidth: %f MHz...") % (bw/1e6) << std::endl;
        usrp->set_rx_bandwidth(bw);
        std::cout << boost::format("Actual RX Bandwidth: %f MHz...") % (usrp->get_rx_bandwidth()/1e6) << std::endl << std::endl;
    }

    //set the antenna
    if (vm.count("ant")) usrp->set_rx_antenna(ant);

    boost::this_thread::sleep(boost::posix_time::seconds(1)); //allow for some setup time

    //Check Ref and LO Lock detect
    std::vector<std::string> sensor_names;
    sensor_names = usrp->get_rx_sensor_names(0);
    if (std::find(sensor_names.begin(), sensor_names.end(), "lo_locked") != sensor_names.end()) {
        uhd::sensor_value_t lo_locked = usrp->get_rx_sensor("lo_locked",0);
        std::cout << boost::format("Checking RX: %s ...") % lo_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(lo_locked.to_bool());
    }
    sensor_names = usrp->get_mboard_sensor_names(0);
    if ((ref == "mimo") and (std::find(sensor_names.begin(), sensor_names.end(), "mimo_locked") != sensor_names.end())) {
        uhd::sensor_value_t mimo_locked = usrp->get_mboard_sensor("mimo_locked",0);
        std::cout << boost::format("Checking RX: %s ...") % mimo_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(mimo_locked.to_bool());
    }
    if ((ref == "external") and (std::find(sensor_names.begin(), sensor_names.end(), "ref_locked") != sensor_names.end())) {
        uhd::sensor_value_t ref_locked = usrp->get_mboard_sensor("ref_locked",0);
        std::cout << boost::format("Checking RX: %s ...") % ref_locked.to_pp_string() << std::endl;
        UHD_ASSERT_THROW(ref_locked.to_bool());
    }

    //create a receive streamer
    uhd::stream_args_t stream_args("fc32"); //complex floats
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    //setup streaming
    uhd::stream_cmd_t stream_cmd(uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE);
    stream_cmd.num_samps = total_num_samps;
    stream_cmd.stream_now = true;
    rx_stream->issue_stream_cmd(stream_cmd);

    //loop until total number of samples reached
    size_t num_acc_samps = 0; //number of accumulated samples
    uhd::rx_metadata_t md;
    std::vector<std::complex<float> > buff(rx_stream->get_max_num_samps());
    uhd::transport::udp_simple::sptr udp_xport = uhd::transport::udp_simple::make_connected(addr, port);

    while(num_acc_samps < total_num_samps){
        size_t num_rx_samps = rx_stream->recv(
            &buff.front(), buff.size(), md
        );

        //handle the error codes
        switch(md.error_code){
        case uhd::rx_metadata_t::ERROR_CODE_NONE:
            break;

        case uhd::rx_metadata_t::ERROR_CODE_TIMEOUT:
            if (num_acc_samps == 0) continue;
            std::cout << boost::format(
                "Got timeout before all samples received, possible packet loss, exiting loop..."
            ) << std::endl;
            goto done_loop;

        default:
            std::cout << boost::format(
                "Got error code 0x%x, exiting loop..."
            ) % md.error_code << std::endl;
            goto done_loop;
        }

        //send complex single precision floating point samples over udp
        udp_xport->send(boost::asio::buffer(buff, num_rx_samps*sizeof(buff.front())));

        num_acc_samps += num_rx_samps;
    } done_loop:

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return EXIT_SUCCESS;
}
Exemple #8
0
int main(int argc, char **argv)
{
	// RNGs
	RNG rng(0);
	RNG rng2(1);

	/*
	 **********************************************************************
	 * Print program information
	 **********************************************************************
	 */
	std::cout << "Psychopath v" << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_PATCH;
#ifdef DEBUG
	std::cout << " (DEBUG build)";
#endif
	std::cout << std::endl;

#ifdef DEBUG
	std::cout << std::endl << "Struct sizes:" << std::endl;
	std::cout << "\tvoid*: " << sizeof(void*) << std::endl;
	std::cout << "\tVec3: " << sizeof(Vec3) << std::endl;
	std::cout << "\tBBox: " << sizeof(BBox) << std::endl;
	std::cout << "\tRay: " << sizeof(Ray) << std::endl;
	std::cout << "\tIntersection: " << sizeof(Intersection) << std::endl;
	std::cout << "\tPotentialInter: " << sizeof(PotentialInter) << std::endl;
	std::cout << "\tBVH::Node: " << sizeof(BVH::Node) << std::endl;
#endif


	/*
	 **********************************************************************
	 * Command-line options.
	 **********************************************************************
	 */
	int spp = SPP;
	int spp_max = SPP;
	float variance_max = -1.0f;
	int threads = std::thread::hardware_concurrency();
	std::string output_path = "default.png";
	std::string input_path = "";
	Resolution resolution(XRES, YRES);

	// Define them
	BPO::options_description desc("Allowed options");
	desc.add_options()
	("help,h", "Print this help message")
	("scenefile,i", BPO::value<std::string>(), "Input scene file")
	("spp,s", BPO::value<int>(), "Number of samples to take per pixel")
	("sppmax,m", BPO::value<int>(), "Max number of samples to take per pixel")
	("variance,v", BPO::value<float>(), "Max image variance")
	("threads,t", BPO::value<int>(), "Number of threads to render with")
	("output,o", BPO::value<std::string>(), "The PNG file to render to")
	("nooutput,n", "Don't save render (for timing tests)")
	("resolution,r", BPO::value<Resolution>()->multitoken(), "The resolution to render at, e.g. 1280 720")
	;

	// Collect them
	BPO::variables_map vm;
	BPO::store(BPO::parse_command_line(argc, argv, desc), vm);
	BPO::notify(vm);

	// Help message
	if (vm.count("help")) {
		std::cout << desc << "\n";
		return 1;
	}

	// Suppress image writing
	Config::no_output = bool(vm.count("nooutput"));

	// Samples per pixel
	if (vm.count("spp")) {
		spp = vm["spp"].as<int>();
		if (spp < 1)
			spp = 1;
		std::cout << "Samples per pixel: " << spp << "\n";
	}
	if (vm.count("sppmax")) {
		spp_max = vm["sppmax"].as<int>();
		if (spp_max < spp)
			spp_max = spp;
		std::cout << "Max samples per pixel: " << spp_max << "\n";
	}
	if (vm.count("variance")) {
		variance_max = vm["variance"].as<float>();
		std::cout << "Max image variance: " << variance_max << "\n";
	}

	// Thread count
	if (vm.count("threads")) {
		threads = vm["threads"].as<int>();
		if (threads < 1)
			threads = 1;
		std::cout << "Threads: " << threads << "\n";
	}

	// Input file
	if (vm.count("scenefile")) {
		input_path = vm["scenefile"].as<std::string>();
		std::cout << "Input scene: " << input_path << "\n";
	}

	// Output file
	if (vm.count("output")) {
		output_path = vm["output"].as<std::string>();
		std::cout << "Output path: " << output_path << "\n";
	}

	// Resolution
	if (vm.count("resolution")) {
		resolution = vm["resolution"].as<Resolution>();
		std::cout << "Resolution: " << resolution.x << " " << resolution.y << "\n";
	}

	std::cout << std::endl;

	/*
	 ***********************************************
	 * Parse scene file, rendering frames as we go.
	 ***********************************************
	 */
	Parser parser(input_path);
	Timer<> total_timer;
	while (true) {
		Timer<> parse_timer;
		std::unique_ptr<Renderer> r {parser.parse_next_frame()};

		if (r == nullptr)
			break;

		std::cout << "Parse time (seconds): " << parse_timer.time() << std::endl;

		Timer<> preprocessing_timer;
		r->scene->finalize();
		std::cout << "Preprocessing time (seconds): " << preprocessing_timer.time() << std::endl;

		// Resolution and sampling overrides
		if (vm.count("resolution"))
			r->set_resolution(resolution.x, resolution.y);
		if (vm.count("spp"))
			r->set_spp(spp);
		if (vm.count("sppmax"))
			r->set_spp_max(spp_max);
		if (vm.count("variance"))
			r->set_variance_max(variance_max);

		/*
		 **********************************************************************
		 * Generate image
		 **********************************************************************
		 */
		r->render(threads);

		std::cout << std::endl << std::endl;
	}

	std::cout << "Total time (seconds): " << std::fixed << std::setprecision(3) << total_timer.time() << std::endl << std::endl;

	return 0;
}
Exemple #9
0
int main(int argc, const char * argv[])
{
	setbuf (stdout, NULL);


#if TARGET_OS_MAC
	{
		thread_extended_policy_data_t		theFixedPolicy;
		theFixedPolicy.timeshare = false;	// set to true for a non-fixed thread
		thread_policy_set(pthread_mach_thread_np(pthread_self()), 
													THREAD_EXTENDED_POLICY, 
													(thread_policy_t)&theFixedPolicy, 
													THREAD_EXTENDED_POLICY_COUNT);

		// We keep a reference to the spawning thread's priority around (initialized in the constructor), 
		// and set the importance of the child thread relative to the spawning thread's priority.
		thread_precedence_policy_data_t		thePrecedencePolicy;
		
		thePrecedencePolicy.importance = 63 - 36;
		thread_policy_set(pthread_mach_thread_np(pthread_self()), 
													THREAD_PRECEDENCE_POLICY, 
													(thread_policy_t)&thePrecedencePolicy, 
													THREAD_PRECEDENCE_POLICY_COUNT);
	}
#endif


// These are the variables that are set up from the input parsing
	char* srcFilePath = NULL;
	char* destFilePath = NULL;
	char* auPresetFile = NULL;
	bool shortMemoryProfile = false;
	OSType manu, subType, type = 0;
	int userSetFrames = -1;
	
	for (int i = 1; i < argc; ++i)
	{
		if (strcmp (argv[i], "-au") == 0) {
            if ( (i + 3) < argc ) {                
                StrToOSType (argv[i + 1], type);
                StrToOSType (argv[i + 2], subType);
                StrToOSType (argv[i + 3], manu);
				i += 3;
			} else {
				printf ("Which Audio Unit:\n%s", usageStr);
				exit(1);
			}
		}
		else if (strcmp (argv[i], "-i") == 0) {
			srcFilePath = const_cast<char*>(argv[++i]);
		}
		else if (strcmp (argv[i], "-o") == 0) {
			destFilePath = const_cast<char*>(argv[++i]);
		}
		else if (strcmp (argv[i], "-p") == 0) {
			auPresetFile = const_cast<char*>(argv[++i]);
		}
		else if (strcmp (argv[i], "-m") == 0) {
			shortMemoryProfile = true;
		}
		else if (strcmp (argv[i], "-f") == 0) {
			sscanf(argv[++i], "%d", &userSetFrames);
		}
		else {
			printf ("%s\n", usageStr);
			exit(1);
		}
	}
	
	if (!type || !srcFilePath) {
		printf ("%s\n", usageStr);
		exit(1);
	}
	if (!destFilePath) {
		if (!shortMemoryProfile) {
			printf ("%s\n", usageStr);
			exit(1);
		}
	}
			// delete pre-existing output file
	if (!shortMemoryProfile) {
		FSRef destFSRef;
		if (FSPathMakeRef((UInt8 *)destFilePath, &destFSRef, NULL) == noErr) {
			// output file exists - delete it
			if (FSDeleteObject(&destFSRef)) {
				printf ("Cannot Delete Output File\n");
				exit(1);
			}
		}
	}
	
	CAComponentDescription desc(type, subType, manu);
	
	CFPropertyListRef presetDict = ReadPresetFromPresetFile(auPresetFile);
	
		// the num of frames to use when processing the file with the Render call
	UInt32 maxFramesToUse = shortMemoryProfile ? 512 : 32768;

		// not set from command line
	if (userSetFrames > 0) {
		maxFramesToUse = userSetFrames; 
	}
		
		// in some settings (for instance a delay with 100% feedback) tail time is essentially infinite
		// so you should safeguard the final OL render stage (post process) which is aimed at pulling the tail through
		// if you want to bypass this completely, just set this to zero.
	Float64 maxTailTimeSecs = 10.;
	
#pragma mark -
#pragma mark __ The driving code
#pragma mark -

	try 
	{
		CAComponent comp(desc);
			
			 // CAAUProcessor's constructor throws... so make sure the component is valid
		if (comp.IsValid() == false) {
			printf ("Can't Find Component\n");
			desc.Print();
			exit(1);
		}
			
		CAAUProcessor processor(comp);
													processor.AU().Print();
		
		CAAudioFile srcFile;
		CAAudioFile destFile; 
		
		srcFile.Open(srcFilePath);

		CAStreamBasicDescription procFormat (srcFile.GetFileDataFormat());
		procFormat.SetCanonical (srcFile.GetFileDataFormat().NumberChannels(), false);

													printf ("Processing Format:\n\t");
													procFormat.Print();
		
		
		if (!shortMemoryProfile) {
			FSRef parentDir;
			CFStringRef filename;
			PosixPathToParentFSRefAndName(destFilePath, parentDir, filename);
			destFile.CreateNew (parentDir, filename, 'AIFF', srcFile.GetFileDataFormat());
			destFile.SetClientFormat (procFormat);
		}
	
		srcFile.SetClientFormat (procFormat);
		
		AUOutputBL outputList(procFormat);

		ReadBuffer* readBuf = NULL;	

#if !CAAF_USE_EXTAUDIOFILE
		UInt64 numInputSamples = srcFile.GetNumberPackets();
#else
		UInt64 numInputSamples = srcFile.GetNumberFrames();
#endif
	
		if (shortMemoryProfile) {
			readBuf = new ReadBuffer;
			readBuf->readData = new AUOutputBL(procFormat);
			readBuf->readFrames = 0;
			UInt32 numFrames = UInt32(procFormat.mSampleRate / 2);
			readBuf->readData->Allocate (numFrames); // half a second of audio data
			readBuf->readData->Prepare(); // half a second of audio data
				
				// read 1/2 second of audio into this read buffer
			srcFile.Read (numFrames, readBuf->readData->ABL());
			
			sInputCallback.inputProc = MemoryInputCallback;
			sInputCallback.inputProcRefCon = readBuf;
			numInputSamples = numFrames;
		}
		else {
			if (desc.IsFConv()) {
				maxFramesToUse = userSetFrames == -1 ? 512 : maxFramesToUse; 
				// some format converter's can call you several times in small granularities
				// so you can't use a large buffer to render or you won't return all of the input data
				// this also lessens the final difference between what you should get and what you do
				// converter units *really* should have a version that are offline AU's to 
				// handle this for you.
				sInputCallback.inputProc = FConvInputCallback;
			} else
				sInputCallback.inputProc = InputCallback;
			
			sInputCallback.inputProcRefCon = &srcFile;
		}
				
		OSStatus result;
		require_noerr (result = processor.EstablishInputCallback (sInputCallback), home);
		require_noerr (result = processor.SetMaxFramesPerRender (maxFramesToUse), home); 
		processor.SetMaxTailTime (maxTailTimeSecs);
		require_noerr (result = processor.Initialize (procFormat, numInputSamples), home);
		if (presetDict) {
			require_noerr (result = processor.SetAUPreset (presetDict), home);
			CFRelease (presetDict);
		}
			// this does ALL of the preflighting.. could be specialise for an OfflineAU type
			// to do this piecemeal and do a progress bar by using the OfflineAUPreflight method
		require_noerr (result = processor.Preflight (), home);
		
		bool isDone; isDone = false;
		bool needsPostProcessing;
		bool isSilence;
		UInt32 numFrames; numFrames = processor.MaxFramesPerRender();

#if CA_AU_PROFILE_TIME
		sReadTime = 0;
		sRenderTime = 0;
#endif
					
PRINT_MARKS();
			// this is the render loop
		while (!isDone) 
		{
											#if CA_AU_PROFILE_TIME 
												UInt64 now = CAHostTimeBase::GetTheCurrentTime(); 
											#endif
			outputList.Prepare(); // have to do this every time...
			require_noerr (result = processor.Render (outputList.ABL(), numFrames, isSilence, &isDone,
											&needsPostProcessing), home);
											#if CA_AU_PROFILE_TIME 
												sRenderTime += (CAHostTimeBase::GetTheCurrentTime() - now);
											#endif

if (!shortMemoryProfile)
	PRINT_PROGRESS(processor.GetOLPercentComplete());
else
	PRINT_PROGRESS(((processor.SampleTime() / numInputSamples) * 100.));
	
			if (numFrames && !shortMemoryProfile)
				destFile.Write (numFrames, outputList.ABL());
		}
			
			// this is the postprocessing if needed
		if (!shortMemoryProfile && needsPostProcessing) 
		{
			isDone = false;
			numFrames = processor.MaxFramesPerRender();
			while (!isDone) {
				outputList.Prepare(); // have to do this every time...
											#if CA_AU_PROFILE_TIME 
												UInt64 now = CAHostTimeBase::GetTheCurrentTime(); 
											#endif
				require_noerr (result = processor.PostProcess (outputList.ABL(), numFrames, 
													isSilence, isDone), home);
											#if CA_AU_PROFILE_TIME 
												sRenderTime += (CAHostTimeBase::GetTheCurrentTime() - now); 
											#endif

PRINT_PROGRESS(processor.GetOLPercentComplete());

				if (numFrames && !shortMemoryProfile)
					destFile.Write (numFrames, outputList.ABL());
			}
		}

printf ("\n");

home:
		if (result) {
			printf ("Exit with bad result:%ld\n", result);
			exit(result);
		}
		
		if (readBuf) {
			delete readBuf->readData;
			delete readBuf;
		}
					
#if CA_AU_PROFILE_TIME
	if (!shortMemoryProfile) {
			// this flushes any remaing data to be written to the disk. 
			// the source file is closed in its destructor of course
		destFile.Close(); 
			// open the file again, to get stats about it for profiling
		destFile.Open(destFilePath);
	}

	SInt64 numWritten;
	if (shortMemoryProfile)
		numWritten = 0;
	else {
#if !CAAF_USE_EXTAUDIOFILE
		numWritten = destFile.GetNumberPackets();
#else
		numWritten = destFile.GetNumberFrames();
#endif
	}

	printf ("Read File Time:%.2f secs for %lld packets (%.1f secs), wrote %lld packets\n", 
						(CAHostTimeBase::ConvertToNanos (sReadTime) / 1.0e9),
						numInputSamples,
						(numInputSamples / procFormat.mSampleRate),
						numWritten);

	if (!shortMemoryProfile) 
	{
#if !CAAF_USE_EXTAUDIOFILE
		UInt64 numOutputSamples = destFile.GetNumberPackets();
#else
		UInt64 numOutputSamples = destFile.GetNumberFrames();
#endif
	
		if (numOutputSamples == numInputSamples) {
			printf ("\tWrote the same number of packets as read\n");
		} else {
			bool expectationMet = !desc.IsOffline(); // we don't have any expectations for offline AU's
			if (processor.LatencySampleCount() || processor.TailSampleCount()) {
				if (numOutputSamples - numInputSamples == processor.TailSampleCount())
					expectationMet = true;
				if (expectationMet)	
					printf ("Correctly wrote \'Read Size + Tail\'. ");
				printf ("AU reports (samples): %ld latency, %ld tail\n", 
										processor.LatencySampleCount(), processor.TailSampleCount());
			}
			if (expectationMet == false) 
			{
				if (numOutputSamples > numInputSamples) {
					printf ("\tWrote %lld packets (%.2f secs) more than read\n", 
								(numOutputSamples - numInputSamples), 
								((numOutputSamples - numInputSamples) / procFormat.mSampleRate));
				} else {
					printf ("\tRead %lld packets (%.2f secs) more than wrote\n", 
								(numInputSamples - numOutputSamples), 
								((numInputSamples - numOutputSamples) / procFormat.mSampleRate));
				}
			}
		}
	}
	
	Float64 renderTimeSecs = CAHostTimeBase::ConvertToNanos (sRenderTime - sReadTime) / 1.0e9;
	printf ("Total Render Time:%.2f secs, using render slice size of %ld frames\n", 
							renderTimeSecs, maxFramesToUse);
	
	Float64 cpuUsage;
	if (shortMemoryProfile)
		cpuUsage = (renderTimeSecs / 0.5) * 100.;
	else
		cpuUsage = (renderTimeSecs / (numInputSamples / procFormat.mSampleRate)) * 100.;
	printf ("CPU Usage for Render Time:%.2f%%\n", cpuUsage);

	CFStringRef str = comp.GetCompName();
	UInt32 compNameLen = CFStringGetLength (str);
	
	CFStringRef presetName = NULL;
	if (auPresetFile) {
		CFPropertyListRef dict;
		if (processor.AU().GetAUPreset (dict) == noErr) {
			presetName = (CFStringRef)CFDictionaryGetValue((CFDictionaryRef)dict, CFSTR("name"));
			CFRelease (dict);
		}
	}

	UInt32 presetLen = presetName ? CFStringGetLength(presetName) : 0;

	char* cstr = (char*)malloc (compNameLen + presetLen + 2 + 1);
	CFStringGetCString (str, cstr, (CFStringGetLength (str) + 1), kCFStringEncodingASCII);
	if (presetName) {
		cstr[compNameLen] = ':';
		cstr[compNameLen+1] = ':';
		CFStringGetCString (presetName, cstr + compNameLen + 2, (CFStringGetLength (presetName) + 1), kCFStringEncodingASCII);
	}
	PerfResult("AudioUnitProcess", EndianU32_NtoB(comp.Desc().componentSubType), cstr, cpuUsage, "%realtime");
	free (cstr);
#endif


	}
	catch (CAXException &e) {
		char buf[256];
		printf("Error: %s (%s)\n", e.mOperation, e.FormatError(buf));
		exit(1);
	}
	catch (...) {
		printf("An unknown error occurred\n");
		exit(1);
	}
			
	return 0;
}
int UHD_SAFE_MAIN(int argc, char *argv[]){
    std::string args, input_str, key, val;

    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "device address args [default = \"\"]")
        ("values", po::value<std::string>(&input_str), "keys+values to read/write, separate multiple by \",\"")
        ("key", po::value<std::string>(&key), "identifiers for new values in EEPROM, separate multiple by \",\" (DEPRECATED)")
        ("val", po::value<std::string>(&val), "the new values to set, omit for readback, separate multiple by \",\" (DEPRECATED)")
        ("read-all", "Read all motherboard EEPROM values without writing")
    ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help") or (not vm.count("key") and not vm.count("values") and not vm.count("read-all"))){
        std::cout << boost::format("USRP Burn Motherboard EEPROM %s") % desc << std::endl;
        std::cout << boost::format(
            "Omit the value argument to perform a readback,\n"
            "Or specify a new value to burn into the EEPROM.\n"
        ) << std::endl;
        return EXIT_FAILURE;
    }

    std::cout << "Creating USRP device from address: " + args << std::endl;
    uhd::device::sptr dev = uhd::device::make(args, uhd::device::USRP);
    uhd::property_tree::sptr tree = dev->get_tree();
    uhd::usrp::mboard_eeprom_t mb_eeprom = tree->access<uhd::usrp::mboard_eeprom_t>("/mboards/0/eeprom").get();
    std::cout << std::endl;

    std::vector<std::string> keys_vec, vals_vec;
    if(vm.count("read-all")) keys_vec = mb_eeprom.keys(); //Leaving vals_vec empty will force utility to only read
    else if(vm.count("values")){
        //uhd::device_addr_t properly parses input values
        uhd::device_addr_t vals(input_str);
        keys_vec = vals.keys();
        vals_vec = vals.vals();
    }
    else{
        std::cout << "WARNING: Use of --key and --val is deprecated!" << std::endl;
        //remove whitespace, split arguments and values 
        boost::algorithm::erase_all(key, " ");
        boost::algorithm::erase_all(val, " ");

        boost::split(keys_vec, key, boost::is_any_of("\"',"));
        boost::split(vals_vec, val, boost::is_any_of("\"',"));

        if((keys_vec.size() != vals_vec.size()) and val != "") {
            //If zero values are given, then user just wants values read to them
            throw std::runtime_error("Number of keys must match number of values!");
        }
    }

    std::cout << "Fetching current settings from EEPROM..." << std::endl;
    for(size_t i = 0; i < keys_vec.size(); i++){
        if (not mb_eeprom.has_key(keys_vec[i])){
            std::cerr << boost::format("Cannot find value for EEPROM[%s]") % keys_vec[i] << std::endl;
            return EXIT_FAILURE;
        }
        std::cout << boost::format("    EEPROM [\"%s\"] is \"%s\"") % keys_vec[i] % mb_eeprom[keys_vec[i]] << std::endl;
    }
    std::cout << std::endl;
    for(size_t i = 0; i < vals_vec.size(); i++){
        if(vals_vec[i] != ""){
            uhd::usrp::mboard_eeprom_t mb_eeprom; mb_eeprom[keys_vec[i]] = vals_vec[i];
            std::cout << boost::format("Setting EEPROM [\"%s\"] to \"%s\"...") % keys_vec[i] % vals_vec[i] << std::endl;
            tree->access<uhd::usrp::mboard_eeprom_t>("/mboards/0/eeprom").set(mb_eeprom);
        }
    }
    std::cout << "Power-cycle the USRP device for the changes to take effect." << std::endl;
    std::cout << std::endl;

    std::cout << "Done" << std::endl;
    return EXIT_SUCCESS;
}
Exemple #11
0
int main(int argc, char** argv) {
  int ngames=1;
  bool print_game=false;

  // Declare the supported options.
  po::options_description desc("Allowed options");
  desc.add_options()
      ("help", "produce help message")
      ("print_game", "Print Game Output")
      ("rand_inputs", "Randomize the inputs")
      ("games", po::value<int>(), "set number of games")
  ;
  
  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);
  
  if (vm.count("help")) {
      cout << desc << "\n";
      return 1;
  }
  
  if(vm.count("print_game")) {
    print_game=true;
  }

  if(vm.count("rand_inputs")) {
    std::srand(std::time(0));
  }

  if (vm.count("games")) {
    ngames=vm["games"].as<int>();
    cout << "Running" << ngames  << "\n";
  } else {
    cout << "Running Game.\n";
  }

  Game game;
  std::map<Player*,int> losses;
  std::vector<Player*> players;

  //for(int i = 0; i < 2; ++i) {
  //  addPlayer(new Player(),game,players);
  //}
  addPlayer(new TimingPlayer(),game,players);
  addPlayer(new WittyPlayer(),game,players);
  addPlayer(new SecretivePlayer(),game,players);
  //addPlayer(new TimingPlayer(),game,players);
  addPlayer(new HoldoutPlayer(),game,players);

  for(int i = 0; i < ngames; ++i) {
    game.shufflePlayers();
    std::set<Player*> losers = game.play(print_game);
    for(Player* loser : losers) {
      losses[loser]+=1;
      if(print_game) {
        cout << loser->player_name() << " " << loser->id() << " lost\n";
      }
    }
  }

  for(Player* p : players) {
    //cout << p->player_name() << " lost " << losses[p] << " games\n";
    cout << p->player_name() << " lost " << std::setprecision(5) <<
(double)losses[p]/(double)ngames << " games\n";
  }
}
Exemple #12
0
int main(int argc, char** argv) {
  bool extract, train;
  int width, height,
      max_horizontal_steps,
      max_vertical_steps,
      video_source;
  std::string output_file;
  std::string model_file;
  std::string positive_source_directory;
  std::string negative_source_directory;

  try {
    namespace po=boost::program_options;
    po::options_description desc("Options");
    desc.add_options()
    ("help,h", "Print help messages")
    ("extract,e", po::value<bool>(&extract)->default_value(true), "Specify whether to extract features")
    ("train,t", po::value<bool>(&train)->default_value(false), "Specify whether to train")
    ("camera,c", po::value<int>(&video_source)->default_value(0), "Specify camera to retrieve test feed")
    ("width,w", po::value<int>(&width)->required(), "Specify train window width")
    ("height,h", po::value<int>(&height)->required(), "Specify train window height")
    ("max_horizontal_steps,mh", po::value<int>(&max_horizontal_steps)->default_value(0), "Specify max horizontal steps the window can take")
    ("max_vertical_steps,mh", po::value<int>(&max_vertical_steps)->default_value(0), "Specify max vertical steps the window can take")
    ("positive,p", po::value<std::string>(&positive_source_directory)->default_value(boost::filesystem::current_path().string<std::string>()+"/positive"), "Specify positive video files directory")
    ("negative,n", po::value<std::string>(&negative_source_directory)->default_value(boost::filesystem::current_path().string<std::string>()+"/negative"), "Specify negative video files direcotry")
    ("output,o", po::value<std::string>(&output_file)->default_value(boost::filesystem::current_path().string<std::string>()+"/features.dump"), "Specify an features file for save/load")
    ("model,m", po::value<std::string>(&model_file)->default_value(boost::filesystem::current_path().string<std::string>()+"/result.model"), "Specify an model file for save/load");

    po::variables_map vm;
    po::store(po::command_line_parser(argc,argv).options(desc).run(), vm);

    if (vm.count("help")) {
      std::cout << "Usage: " << argv[0] << " [options]" << std::endl;
      std::cout << desc;
      return 0;
    }

    po::notify(vm);
  } catch(std::exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
    return 1;
  } catch(...) {
    std::cerr << "Exception of unknown type!" << std::endl;
    return 1;
  }

  const cv::Size window_size=cv::Size(width, height);

  std::vector<maav::Features> features_collection;
  std::vector<unsigned int> divider;

  maav::HOGExtractor extractor(window_size);

  if(extract) {
    maav::FeatureExtractMethod extract_method(extractor, features_collection);
    boost::function<void (const cv::Mat &)> f=boost::ref(extract_method);

    boost::filesystem::path positive_dir(positive_source_directory);
    if(boost::filesystem::is_directory(positive_dir)) {
      boost::filesystem::directory_iterator dir_iter(positive_dir), eod;

      unsigned int counter=0;
      BOOST_FOREACH(boost::filesystem::path const &file_path, std::make_pair(dir_iter, eod)) {
        maav::LoadEachFrameFromFile(file_path.string<std::string>(), f);
        for(unsigned int i=0;i<(features_collection.size()-divider.size());i++) {
          divider.push_back(counter);
        }
        counter++;
      }
    }

    boost::filesystem::path negative_dir(positive_source_directory);
    if(boost::filesystem::is_directory(negative_dir)) {
      boost::filesystem::directory_iterator dir_iter(negative_dir), eod;

      BOOST_FOREACH(boost::filesystem::path const &file_path, std::make_pair(dir_iter, eod)) {
        maav::LoadEachFrameFromFile(file_path.string<std::string>(), f);
      }
    }
int main(int argc, char** argv)
{
  use_case::UseCaseEnvironment use_case_environment(&argc, &argv);
  stk::ParallelMachine comm = use_case_environment.m_comm;

  //----------------------------------
  // Broadcast argc and argv to all processors.

  stk::BroadcastArg b_arg(comm, argc, argv);

  //----------------------------------
  // Process the broadcast command line arguments

  bopt::options_description desc("options");

  stk::get_options_description().add(desc);

  int num_trials = 0;
  int nthreads = 1;
  int bucket_size = 1000;

  desc.add_options()
    ("help,h",        "produce help message")
    ("performance",   "run performance test [14/14a/blas only]")
    ("mesh,m",        bopt::value<std::string>(), "mesh file. Use name of form 'gen:NxMxL' to internally generate a hex mesh of size N by M by L intervals. See GeneratedMesh documentation for more options. Use 'gears' to generate the gears mesh." )
    ("directory,d",   bopt::value<std::string>(), "working directory with trailing '/'" )
    ("output-log,o",  bopt::value<std::string>(), "output log path" )
    ("runtest,r",     bopt::value<std::string>(), "runtest pid file" )
    ("threads",       bopt::value<int>(&nthreads)->default_value(1),   "number of threads [14/14a/blas only]")
    ("trials",        bopt::value<int>(&num_trials)->default_value(1),   "number of trials (execute loops) [14/14a/blas only]")
    ("bucket_size",    bopt::value<int>(&bucket_size)->default_value(1000),   "size of buckets used internally in stk::mesh [14/14a/blas only]")
    ("tbb",           "Use Threaded Building Blocks algorithm thread runner [14/14a/blas only]")
    ("tpi",           "Use Thread Pool Interface algorithm thread runner [14/14a/blas only]")
    ("nonthreaded",   "Run algorithms non-threaded [default] [14/14a/blas only]")
    ( use_case_7 ,   "use case 7" )
    ( use_case_blas , "use case blas (fill, axpby, dot, norm)" )
    ( use_case_14 ,   "use case 14 (hex internal force algorithm)" )
    ( use_case_14a ,  "use case 14a (hex internal force algorithm)" )
    ( use_case_24 ,   "use case 24 " );

  bopt::variables_map vm;
  try {
    bopt::store(bopt::parse_command_line(b_arg.m_argc, b_arg.m_argv, desc), vm);
    bopt::notify(vm);
  }
  catch (std::exception &x) {
    std::cout << x.what() << std::endl;
    std::exit(1);
  }


  //----------------------------------

  if (vm.count("help")) {
    std::cout << desc << "\n";
    std::exit(EXIT_SUCCESS);
  }

  bool run_performance_test = vm.count( "performance" ) > 0;

  std::string thread_runner = "NonThreaded";
  if (vm.count("tbb"))
    thread_runner = "TBB";
  if (vm.count("tpi"))
    thread_runner = "TPI";
//   if (vm.count("dgb"))
//     thread_runner = "DGB";
  if (vm.count("nonthreaded"))
    thread_runner = "NonThreaded";

  std::string working_directory = "";
  std::string in_filename = "";
  std::string in_filetype = "exodusii";
  if (vm.count("mesh")) {
    in_filename = boost::any_cast<std::string>(vm["mesh"].value());;

    if (strncasecmp("gen:", in_filename.c_str(), 4) == 0) {
      // Strip off the 'gen:' prefix and set the type to "generated"
      in_filename = in_filename.substr(4, in_filename.size());
      in_filetype = "generated";
    }

    if (strncasecmp("gears:", in_filename.c_str(), 6) == 0) {
      // Strip off the 'gears:' prefix and set the type to "gears"
      in_filename = in_filename.substr(6, in_filename.size());
      in_filetype = "gears";
    }

    if (vm.count("directory")) {
      working_directory = boost::any_cast<std::string>(vm["directory"].value());
    }
  } else {
    std::cout << "OPTION ERROR: The '--mesh <filename>' option is required for all use cases!\n";
    std::exit(EXIT_FAILURE);
  }

  bool success = false;

  if ( vm.count( use_case_7 ) ) {

    if (in_filetype != "generated") {
      std::cout << "OPTION ERROR: For use case 7, only the 'generated' mesh option is supported!\n";
      std::exit(EXIT_FAILURE);
    }

    success = stk::app::use_case_7_driver( comm , run_performance_test , in_filename , nthreads, thread_runner );
  }

  else if ( vm.count( use_case_blas ) ) {
    success = stk::app::use_case_blas_driver(comm, nthreads, num_trials, working_directory,
                                             in_filename, in_filetype, thread_runner, bucket_size,
                                             run_performance_test);
  }

  else if ( vm.count( use_case_14 ) ) {
    success = stk::app::use_case_14_driver(comm, nthreads, num_trials, working_directory,
                                           in_filename, in_filetype, thread_runner, bucket_size,
                                           run_performance_test);
  }

  else if ( vm.count( use_case_14a ) ) {
    success = stk::app::use_case_14a_driver(comm, nthreads, num_trials, working_directory,
                                            in_filename, in_filetype, thread_runner, bucket_size,
                                            run_performance_test);
  }

  else if ( vm.count( use_case_24 ) ) {
    if (in_filetype == "generated") {
      std::cout << "OPTION ERROR: The 'generated mesh option' option is not supported for use case 24!\n";
      std::exit(EXIT_FAILURE);
    }

    if (in_filetype == "gears") {
      std::cout << "OPTION ERROR: The 'gears mesh option' option is not supported for use case 24!\n";
      std::exit(EXIT_FAILURE);
    }

    success = stk::app::use_case_24_driver( comm, working_directory, in_filename, "1mCube.e" );
  }
  else {
    std::cout << "OPTION ERROR: Missing a use case selection option.  Use --help option to see valid options.\n";
    std::exit(EXIT_FAILURE);
  }

  use_case::print_status(comm, success);

  return 0;
}
Exemple #14
0
int realmain(int argc, char** argv)
{
    while(!FARender::Renderer::get()) {}

    FARender::Renderer& renderer = *FARender::Renderer::get();
    Input::InputManager& input = *Input::InputManager::get();

    size_t levelNum;

    boost::program_options::options_description desc("Options");
    desc.add_options()
        ("help,h", "Print help")
        ("level,l", boost::program_options::value<size_t>(&levelNum)->default_value(0), "Level number to load (0-4)");

    boost::program_options::variables_map vm; 
    try 
    { 
        boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);

        if(vm.count("help"))
        {
            std::cout << desc << std::endl;
            return 0;
        }
        
        boost::program_options::notify(vm);

        if(levelNum > 4)
            throw boost::program_options::validation_error(
                boost::program_options::validation_error::invalid_option_value, "level");
    }
    catch(boost::program_options::error& e)
    {
        std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
        std::cerr << desc << std::endl;
        return 1;
    }


    DiabloExe::DiabloExe exe;
    FAWorld::World world;

    FALevelGen::FAsrand(time(NULL));

    std::vector<Level::Level*> levels(5);

    size_t currentLevel = levelNum;

    Level::Level* level;

    if(!(level = getLevel(levelNum, exe)))
    {
        done = true;
    }
    else
    {
        levels[currentLevel] = level;
        setLevel(levelNum, exe, world, renderer, *level);
    }
    
    FAWorld::Player* player = world.getPlayer();

    if(levelNum == 0)
        player->mPos = FAWorld::Position(75, 68);
    else
        player->mPos = FAWorld::Position(level->upStairsPos().first, level->upStairsPos().second);

    boost::posix_time::ptime last = boost::posix_time::microsec_clock::local_time();
    
    std::pair<size_t, size_t> destination = player->mPos.current();
    
    // Main game logic loop
    while(!done)
    {
        if(mouseDown)
        {
            destination = renderer.getClickedTile(xClick, yClick);
            if(click)
                level->activate(destination.first, destination.second);

            click = false;
        }

        input.processInput();

        if(changeLevel)
        {
            int32_t tmp = currentLevel + changeLevel;
            if(tmp >= 0 && tmp < (int32_t)levels.size())
            {
                currentLevel = tmp;

                if(levels[currentLevel] == NULL)
                    levels[currentLevel] = getLevel(currentLevel == 0 ? 0 : 1, exe);

                level = levels[currentLevel];
                
                if(changeLevel == -1)
                    player->mPos = FAWorld::Position(level->downStairsPos().first, level->downStairsPos().second);
                else
                    player->mPos = FAWorld::Position(level->upStairsPos().first, level->upStairsPos().second);
                
                setLevel(currentLevel, exe, world, renderer, *level);

            }
            
            changeLevel = 0;
        }

        boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
        
        while((size_t)(now.time_of_day().total_milliseconds() - last.time_of_day().total_milliseconds()) < 1000/FAWorld::World::ticksPerSecond)
        {
            boost::this_thread::sleep(boost::posix_time::milliseconds(1));
            now = boost::posix_time::microsec_clock::local_time();
        }

        last = now;

        if(player->mPos.current() != destination)
        {
            if(player->mPos.mDist == 0)
            {
                std::pair<float, float> vector = Misc::getVec(player->mPos.current(), destination);

                if(!player->mPos.mMoving)
                {
                    player->mPos.mMoving = true;
                    player->setAnimation(FAWorld::AnimState::walk);
                }

                player->mPos.mDirection = Misc::getVecDir(vector);
            }
        }
        else if(player->mPos.mMoving && player->mPos.mDist == 0)
        {
            player->mPos.mMoving = false;
            player->setAnimation(FAWorld::AnimState::idle);
        }

        if(!noclip && !(*level)[player->mPos.next().first][player->mPos.next().second].passable())
        {
            player->mPos.mMoving = false;
            player->setAnimation(FAWorld::AnimState::idle);
        }

        world.update();
        
        FARender::RenderState* state = renderer.getFreeState();
        
        state->mPos = player->mPos;

        world.fillRenderState(state);

        renderer.setCurrentState(state);
    }

    renderer.stop();    

    while(!renderDone) {} // have to wait until the renderer stops before destroying all our locals

    for(size_t i = 0; i < levels.size(); i++)
        delete levels[i];

    return 0;
}
Exemple #15
0
int app_proxy(
    int argc, char const * const * argv, const char * copyright_notice
  , CryptoContext & cctx
  , ExtraOptions const & extrax_options, ExtracOptionChecker extrac_options_checker
  , PreLoopFn pre_loop_fn = PreLoopFn()
) {
    setlocale(LC_CTYPE, "C");

    const unsigned uid = getuid();
    const unsigned gid = getgid();

    unsigned euid = uid;
    unsigned egid = gid;

    std::string config_filename = CFG_PATH "/" RDPPROXY_INI;

    program_options::options_description desc({
        {'h', "help", "produce help message"},
        {'v', "version", "show software version"},
        {'k', "kill", "shut down rdpproxy"},
        {'n', "nodaemon", "don't fork into background"},

        {'u', "uid", &euid, "run with given uid"},

        {'g', "gid", &egid, "run with given gid"},

        //{'t', "trace", "trace behaviour"},

        {'c', "check", "check installation files"},

        {'f', "force", "remove application lock file"},

        {'i', "inetd", "launch redemption with inetd like launcher"},

        {"config-file", &config_filename, "used an another ini file"},

        //{"test", "check Inifile syntax"}
    });

    for (extra_option const & extra : extrax_options) {
        desc.add({extra.option_long, extra.description});
    }

    auto options = program_options::parse_command_line(argc, const_cast<char**>(argv), desc);

    if (options.count("kill")) {
        int status = shutdown(PID_PATH "/redemption/" LOCKFILE);
        if (status){
            // TODO check the real error that occured
            std::clog << "problem opening " << PID_PATH "/redemption/" LOCKFILE  << "."
            " Maybe rdpproxy is not running\n";
        }
        return status;
    }
    if (options.count("help")) {
        std::cout << copyright_notice << "\n\n";
        std::cout << "Usage: rdpproxy [options]\n\n";
        std::cout << desc << std::endl;
        return 0;
    }
    if (options.count("version")) {
        std::cout << copyright_notice << std::endl;
        return 0;
    }

    {
        bool quit = false;
        if (int status = extrac_options_checker(options, &quit)) {
            return status;
        }
        else if (quit) {
            return 0;
        }
    }

    openlog("rdpproxy", LOG_CONS | LOG_PERROR, LOG_USER);

    if (options.count("check")) {
        bool user_check_file_result  =
            ((uid != euid) || (gid != egid)) ?
            CheckFile::check(user_check_file_list) : true;
        /*
          setgid(egid);
          setuid(euid);
        */
        bool euser_check_file_result = CheckFile::check(euser_check_file_list);
        /*
          setgid(gid);
          setuid(uid);
        */

        if ((uid != euid) || (gid != egid)) {
            CheckFile::ShowAll(user_check_file_list, uid, gid);
        }
        CheckFile::ShowAll(euser_check_file_list, euid, egid);

        if (!user_check_file_result || !euser_check_file_result)
        {
            if ((uid != euid) || (gid != egid))
            {
                CheckFile::ShowErrors(user_check_file_list, uid, gid);
            }
            CheckFile::ShowErrors(euser_check_file_list, euid, egid);

            LOG(LOG_INFO, "%s",
                "Please verify that all tests passed. If not, "
                    "you may need to remove " PID_PATH "/redemption/"
                    LOCKFILE " or reinstall rdpproxy if some configuration "
                    "files are missing.");
        }
        return 0;
    }

    if (options.count("inetd")) {
        redemption_new_session(cctx, config_filename.c_str());
        return 0;
    }

    // if -f (force option) is set
    // force kill running rdpproxy
    // force remove pid file
    // don't check if it fails (proxy may be allready stopped)
    // and try to continue normal start process afterward

    if (mkdir(PID_PATH "/redemption", 0700) < 0){
        // TODO check only for relevant errors (exists with expected permissions is OK)
    }

    if (chown(PID_PATH "/redemption", euid, egid) < 0){
        LOG(LOG_INFO, "Failed to set owner %u.%u to " PID_PATH "/redemption", euid, egid);
        return 1;
    }

    if (options.count("force")){
        shutdown(PID_PATH  "/redemption/" LOCKFILE);
    }

    if (0 == access(PID_PATH "/redemption/" LOCKFILE, F_OK)) {
        std::clog <<
        "File " << PID_PATH "/redemption/" LOCKFILE << " already exists. "
        "It looks like rdpproxy is already running, "
        "if not, try again with -f (force) option or delete the " PID_PATH "/redemption/" LOCKFILE " file and try again\n";
        return 1;
    }


    /* write the pid to file */
    int fd = open(PID_PATH "/redemption/" LOCKFILE, O_WRONLY | O_CREAT, S_IRWXU);
    if (fd == -1) {
        std::clog
        <<  "Writing process id to " PID_PATH "/redemption/" LOCKFILE " failed. Maybe no rights ?"
        << " : " << errno << ":'" << strerror(errno) << "'\n";
        return 1;
    }
    {
        io::posix::fdbuf file(fd);
        const int pid = getpid();
        char text[256];
        size_t lg = snprintf(text, 255, "%d", pid);
        if (file.write(text, lg) == -1) {
            LOG(LOG_ERR, "Couldn't write pid to %s: %s", PID_PATH "/redemption/" LOCKFILE, strerror(errno));
            return 1;
        }
    }

    if (!options.count("nodaemon")) {
        daemonize(PID_PATH "/redemption/" LOCKFILE);
    }

    Inifile ini;
    { ConfigurationLoader cfg_loader(ini.configuration_holder(), config_filename.c_str()); }

    OpenSSL_add_all_digests();

    if (!ini.get<cfg::globals::enable_ip_transparent>()) {
        if (setgid(egid) != 0){
            LOG(LOG_ERR, "Changing process group to %u failed with error: %s\n", egid, strerror(errno));
            return 1;
        }
        if (setuid(euid) != 0){
            LOG(LOG_ERR, "Changing process user to %u failed with error: %s\n", euid, strerror(errno));
            return 1;
        }
    }

    pre_loop_fn(ini);

    LOG(LOG_INFO, "ReDemPtion " VERSION " starting");
    redemption_main_loop(ini, cctx, euid, egid, std::move(config_filename));

    /* delete the .pid file if it exists */
    /* don't care about errors. */
    /* If we are not in daemon mode this file will not exists, */
    /* hence some errors are expected */
    unlink(PID_PATH "/redemption/" LOCKFILE);

    return 0;
}
Exemple #16
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    
  //Seting priority in the processor to run faster -> run with sudo
  if (!(uhd::set_thread_priority_safe(1,true))) {
    std::cout << "Problem setting thread priority" << std::endl;
    return 1;
  };
  //variables to be set by po -> Set when initializing the rx program
  //double seconds_in_future=0.01;
  size_t total_num_samps;
  double rx_rate, freq, LOoffset;
  bool use_external_10MHz;
  double scaling_8bits;
  std::string filename;
  float gain;
  bool realTime;
  uhd::device_addr_t dev_addr;
  uhd::usrp::multi_usrp::sptr dev;
  uhd::tune_result_t tr;
  uhd::stream_args_t stream_args;
  uhd::rx_streamer::sptr rx_stream;


  //setup the program options-> Passing it from terminal with boost library 
  po::options_description desc("Allowed options");
  desc.add_options()
    ("help", "help message")
    ("nsamps", po::value<size_t>(&total_num_samps)->default_value(1000), "total number of samples to receive")
    ("rxrate", po::value<double>(&rx_rate)->default_value(100e6/4), "rate of incoming samples")
    ("freq", po::value<double>(&freq)->default_value(5.5e9), "rf center frequency in Hz")
    ("LOoffset", po::value<double>(&LOoffset)->default_value(10e6), "Offset between main LO and center frequency")
    ("10MHz",po::value<bool>(&use_external_10MHz)->default_value(false), "external 10MHz on 'REF CLOCK' connector (true=1=yes)")
    //  ("PPS",po::value<bool>(&trigger_with_pps)->default_value(false), "trigger reception with 'PPS IN' connector (true=1=yes)")
    ("filename",po::value<std::string>(&filename)->default_value("data_from_usrp.dat"), "output filename") 
    ("gain",po::value<float>(&gain)->default_value(30), "set the receiver gain") 
    ("8bits_scaling",po::value<double>(&scaling_8bits)->default_value(0.0), 
     "input scaling (invers) when 8bits is used, set to zero to get 16bits")
      
    /////////////////////////////
    ("realTime",po::value<bool>(&realTime)->default_value(true), "receives in loop and compares with synch sequence")
    ;
   
  //Variables stored in boost objects
  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  //print the help message
  if (vm.count("help")){
    std::cout << boost::format("rx %s") % desc << std::endl;
    return ~0;
  }

  ///////////Set device variables to read data////////////////
    
  dev_addr["addr0"]="192.168.10.2";
  dev = uhd::usrp::multi_usrp::make(dev_addr);//Create the device

  //receiving format
  stream_args.cpu_format="sc16";
  if (scaling_8bits==0.0) {
    stream_args.otw_format="sc16";     
  } else {
    stream_args.otw_format="sc8";
    std::stringstream temp_ss;
    temp_ss << scaling_8bits;
    stream_args.args["peak"]=temp_ss.str();
  };

  rx_stream=dev->get_rx_stream(stream_args); //set/get the streamer values to the device

  uhd::clock_config_t my_clock_config; 

  /*
    if (trigger_with_pps) {
    my_clock_config.pps_source=uhd::clock_config_t::PPS_SMA; 
    };
  */

  if (use_external_10MHz) { 
    my_clock_config.ref_source=uhd::clock_config_t::REF_SMA; 
  };  

  /////////////////Create an USRP device////////////////////////
  std::cout << std::endl;
  //uhd::device::sptr udev = dev->get_device();
  dev->set_rx_rate(rx_rate);

  bool is_xcvr2450=false;
  uhd::dict<std::string, std::string> rx_info;    
  rx_info=dev->get_usrp_rx_info(0);

  if (rx_info.has_key("rx_subdev_name")) {
    std::string str=rx_info.get("rx_subdev_name");
    uint temp=str.find("XCVR2450");
    if (temp<str.length()) {
      is_xcvr2450=true;
    };
  };

  if (is_xcvr2450) {
    dev->set_tx_antenna("J2");
    dev->set_rx_antenna("J1");      
    //uhd::meta_range_t range=dev->get_tx_bandwidth_range();

    if (LOoffset>=9e6) {
      dev->set_rx_bandwidth(3.96e+07);
    };      
  };

  std::cout << "rx_rate=" << rx_rate << std::endl;
  std::cout << "freq=" << freq << std::endl;
  std::cout << "gain=" << gain << std::endl;
  uhd::tune_request_t trq(freq,LOoffset); 
  //dev->set_rx_bandwidth(36e6);
  tr=dev->set_rx_freq(trq);
  dev->set_rx_gain(gain);

  std::cout << "tr=" << tr.actual_rf_freq << std::endl;


  if (use_external_10MHz) {
    dev->set_clock_config(my_clock_config); // PZ
    usleep(1e6); // Wait for the 10MHz to lock
  }; 

  size_t buffer_size=1000; // Select buffer size

  uint nDetect=1000;
  

  dev->set_time_now(uhd::time_spec_t(0.0));
 
  std::cout << boost::format("Setting device timestamp to 0...") << std::endl;

  

   
  //////////////////////////////////Read data to buff_short and do processing////////////


  //Launch threads
  sem_init(&isReady, 0,0); 
  std::thread storeT(storeDataX, rx_stream, dev, buffer_size, nDetect);
  std::thread detectionT(detection, nDetect);

  storeT.join();
  detectionT.join();

  //finished
  std::cout << std::endl << "Done receiving!" << std::endl << std::endl; 

  return 0;
}
bool parseOptions( int argc, char** argv, ProgramOptions &options )
throw (std::runtime_error )
{
    try
    {
        // add help message
        std::stringstream desc_stream;
        desc_stream << "Usage splash2txt [options] <input-file>" << std::endl;

        po::options_description desc( desc_stream.str( ) );

        std::string slice_string = "";
        std::string filemode = "splash";
        
        const std::string filemodeOptions = "[splash]";

        // add possible options
        desc.add_options( )
            ( "help,h", "print help message" )
            ( "verbose,v", "verbose output, print status messages" )
            ( "mode,m", po::value< std::string > ( &filemode )->default_value( filemode ), (std::string("File Mode ") + filemodeOptions).c_str() )
            ( "list,l", "list the available datasets for an input file" )
            ( "input-file", po::value< std::string > ( &options.inputFile ), "parallel input file" )
            ( "output-file,o", po::value< std::string > ( &options.outputFile ), "output file (otherwise stdout)" )
            ( "step,s", po::value<uint32_t > ( &options.step )->default_value( options.step ), "requested simulation step" )
            ( "data,d", po::value<std::vector<std::string> > ( &options.data )->multitoken( ), "name of datasets to print" )
            ( "slice", po::value< std::string > ( &slice_string )->default_value( "xy" ), "dimensions of slice for field data, e.g. xy" )
            /// \todo if the standard offset value would be the MIDDLE of the global simulation area, it would be awesome
            ( "offset", po::value<size_t > ( &options.sliceOffset )->default_value( 0 ), "offset of slice in dataset" )
            ( "delimiter", po::value<std::string>( &options.delimiter )->default_value( " " ), "select a delimiter for data elements. default is a single space character" )
            ( "no-units", "no conversion of stored data elements with their respective unit" )
            ;

        po::positional_options_description pos_options;
        pos_options.add( "input-file", -1 );

        // parse command line options and store values in vm
        po::variables_map vm;
        po::store( po::command_line_parser( argc, argv ).
                   options( desc ).positional( pos_options ).run( ), vm );
        po::notify( vm );

        // print help message and quit program if requested or if required parameters are missing
        if ( vm.count( "help" ) || !vm.count( "input-file" ) ||
             ( !vm.count( "data" ) && !vm.count( "list" ) ) ||
             !vm.count( "step" ) )
        {
            errorStream << desc << "\n";
            return false;
        }
        
        options.fileMode = FM_SPLASH;

        // re-parse wrong typed input files to valid format, if possible
        //   find _X.h5 with syntax at the end and delete it
        boost::regex filePattern( "_.*\\.h5",
                                  boost::regex_constants::icase |
                                  boost::regex_constants::perl );
        options.inputFile = boost::regex_replace( options.inputFile, filePattern, "" );

        // set various flags
        options.verbose = vm.count( "verbose" ) != 0;
        options.listDatasets = vm.count( "list" ) != 0;
        options.toFile = vm.count( "output-file" ) != 0;
        options.applyUnits = vm.count( "no-units" ) == 0;

        if ( vm.count( "slice" ) ^ vm.count( "offset" ) )
        {
            errorStream << "Parameters 'slice' and 'offset' require each other." << std::endl;
            errorStream << desc << "\n";
            return false;
        }

        if ( vm.count( "slice" ) )
        {
            bool sliceFound = false;
            options.fieldDims.set( 0, 0, 0 );
            for ( int i = 0; i < numAllowedSlices; ++i )
            {
                if ( slice_string.compare( allowedSlices[i] ) == 0 )
                {
                    sliceFound = true;
                    options.isReverseSlice = false;
                    break;
                }

                if ( slice_string.compare( allowedReverseSlices[i] ) == 0 )
                {
                    sliceFound = true;
                    options.isReverseSlice = true;
                    break;
                }
            }

            if ( !sliceFound )
            {
                errorStream << "Invalid input for parameter 'slice'. Accepted: xy, xz, yz, yx, zx, zy" << std::endl;
                errorStream << desc << "\n";
                return false;
            }

            if ( slice_string.find( 'x' ) != std::string::npos )
                options.fieldDims[0] = 1;

            if ( slice_string.find( 'y' ) != std::string::npos )
                options.fieldDims[1] = 1;

            if ( slice_string.find( 'z' ) != std::string::npos )
                options.fieldDims[2] = 1;
        }

    }
    catch ( boost::program_options::error e )
    {
        throw std::runtime_error( "Error parsing command line options!" );
    }

    return true;
}
int main(int argc, char *argv[])
{
    boost::program_options::options_description desc("Options");
    desc.add_options()
    ("version", "produce version message")
    ("help", "produce help message")
    ("shm", boost::program_options::value< std::string > (), "shared memory segment name")
    ("port", boost::program_options::value< std::string > (), "the TCP port that the traffic server is listening on to allow agents to communicate with the traffic simulation, the default value is 10007")
    ("team", boost::program_options::value< std::string > (), "team name")
    ;

    boost::program_options::variables_map vm;
    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
    boost::program_options::notify(vm);

    if (vm.count("version")) {
        std::cout << "OOCWC Raxicab (SamuSmartCity) - rObOCar World Championship, Sample (My) SHM Client" << std::endl
                  << "Copyright (C) 2014, 2015, 2016 Norbert Bátfai\n" << std::endl
                  << "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>" << std::endl
                  << "This is free software: you are free to change and redistribute it." << std::endl
                  << "There is NO WARRANTY, to the extent permitted by law." << std::endl;
        return 0;
    }

    if (vm.count("help")) {
        std::cout << "OOCWC Raxicab (SamuSmartCity) - rObOCar World Championship home page: https://github.com/nbatfai/SamuSmartCity" << std::endl;
        std::cout << desc << std::endl;
        std::cout << "Please report bugs to: [email protected]" << std::endl;
        return 0;
    }

    std::string shm;
    if (vm.count("shm"))
        shm.assign(vm["shm"].as < std::string > ());
    else
        shm.assign("JustineSharedMemory");

    std::string port;
    if (vm.count("port"))
        port.assign(vm["port"].as < std::string > ());
    else
        port.assign("10007");

    std::string team;
    if (vm.count("team"))
        team.assign(vm["team"].as < std::string > ());
    else
        team.assign("Norbi");

    // If you use this sample you should add your copyright information here too:
    /*
    std::cout << "This SHM Client program has been modified by <Your Name>" << std::endl
    << "Copyright (C) 2014, 2015 Norbert Bátfai" << std::endl
    << "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>" << std::endl
    */

    // Do not remove this copyright notice!
    std::cout << "OOCWC Raxicab (SamuSmartCity) - rObOCar World Championship, Sample (My) SHM Client" << std::endl
              << "Copyright (C) 2014, 2015, 2016 Norbert Bátfai" << std::endl
              << "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>" << std::endl
              << "This is free software: you are free to change and redistribute it." << std::endl
              << "There is NO WARRANTY, to the extent permitted by law." << std::endl;

    justine::sampleclient::MyShmClient myShmClient {shm.c_str(), team };

    try {
        boost::asio::io_service io_service;
        myShmClient.start10(io_service, port.c_str());
        //myShmClient.start(io_service, port.c_str());
    } catch (std::exception &e) {
        std::cerr << "Exception: " << e.what() << "\n";
    }

}
Exemple #19
0
/***********************************************************************
 * Main code + dispatcher
 **********************************************************************/
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args;
    double duration;
    double rx_rate, tx_rate;
    std::string rx_otw, tx_otw;
    std::string rx_cpu, tx_cpu;
    std::string mode;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "single uhd device address args")
        ("duration", po::value<double>(&duration)->default_value(10.0), "if random, specify duration for the test in seconds")
        ("rx_rate", po::value<double>(&rx_rate), "specify to perform a RX rate test (sps)")
        ("tx_rate", po::value<double>(&tx_rate), "specify to perform a TX rate test (sps)")
        ("rx_otw", po::value<std::string>(&rx_otw)->default_value("sc16"), "specify the over-the-wire sample mode for RX")
        ("tx_otw", po::value<std::string>(&tx_otw)->default_value("sc16"), "specify the over-the-wire sample mode for TX")
        ("rx_cpu", po::value<std::string>(&rx_cpu)->default_value("fc32"), "specify the host/cpu sample mode for RX")
        ("tx_cpu", po::value<std::string>(&tx_cpu)->default_value("fc32"), "specify the host/cpu sample mode for TX")
        ("mode", po::value<std::string>(&mode)->default_value("none"), "multi-channel sync mode option: none, mimo")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help") or (vm.count("rx_rate") + vm.count("tx_rate")) == 0){
        //std::cout << boost::format("UHD Transport Hammer - %s") % desc << std::endl;
        std::cout <<
        "UHD Transport Hammer: a transport layer stress test that continuously\n"
        "calls for random amounts of TX and RX samples\n\n";
        std::cout << desc << std::endl <<
        "    Specify --rx_rate for a receive-only test.\n"
        "    Specify --tx_rate for a transmit-only test.\n"
        "    Specify both options for a full-duplex test.\n"
        << std::endl;
        return ~0;
    }

    //create a usrp device
    std::cout << std::endl;
    uhd::device_addrs_t device_addrs = uhd::device::find(args, uhd::device::USRP);
    if (not device_addrs.empty() and device_addrs.at(0).get("type", "") == "usrp1"){
        std::cerr << "*** Warning! ***" << std::endl;
        std::cerr << "Results will be inaccurate on USRP1 due to insufficient features.\n" << std::endl;
    }
    std::cout << boost::format("Creating the usrp device with: %s...") % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);
    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;

    if (mode == "mimo"){
        usrp->set_clock_source("mimo", 0);
        usrp->set_time_source("mimo", 0);
        boost::this_thread::sleep(boost::posix_time::seconds(1));
    }

    boost::thread_group thread_group;

    //spawn the receive test thread
    if (vm.count("rx_rate")){
        usrp->set_rx_rate(rx_rate);
        //create a receive streamer
        uhd::stream_args_t stream_args(rx_cpu, rx_otw);
        for (size_t ch = 0; ch < usrp->get_num_mboards(); ch++) //linear channel mapping
            stream_args.channels.push_back(ch);
        uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);
        thread_group.create_thread(boost::bind(&rx_hammer, usrp, rx_cpu, rx_stream));
    }

    //spawn the transmit test thread
    if (vm.count("tx_rate")){
        usrp->set_tx_rate(tx_rate);
        //create a transmit streamer
        uhd::stream_args_t stream_args(tx_cpu, tx_otw);
        for (size_t ch = 0; ch < usrp->get_num_mboards(); ch++) //linear channel mapping
            stream_args.channels.push_back(ch);
        uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args);
        thread_group.create_thread(boost::bind(&tx_hammer, usrp, tx_cpu, tx_stream));
        thread_group.create_thread(boost::bind(&tx_hammer_async_helper, tx_stream));
    }

    //sleep for the required duration
    const long secs = long(duration);
    const long usecs = long((duration - secs)*1e6);
    boost::this_thread::sleep(boost::posix_time::seconds(secs) + boost::posix_time::microseconds(usecs));

    //interrupt and join the threads
    thread_group.interrupt_all();
    thread_group.join_all();

    //print summary
    std::cout << std::endl << boost::format(
        "Transport Hammer summary:\n"
        "  Num received samples:    %u\n"
        "  Num dropped samples:     %u\n"
        "  Num overflows detected:  %u\n"
        "  Num transmitted samples: %u\n"
        "  Num sequence errors:     %u\n"
        "  Num underflows detected: %u\n"
    ) % num_rx_samps % num_dropped_samps % num_overflows % num_tx_samps % num_seq_errors % num_underflows << std::endl;

    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    return EXIT_SUCCESS;
}
int main ( int argc, char* argv[] )
{
  boost::program_options::options_description desc ( "Options" );
  desc.add_options()
  ( "version", "produce version message" )
  ( "help", "produce help message" )
  ( "osm", boost::program_options::value< std::string > (), "OSM file name" )
  ( "city", boost::program_options::value< std::string > (), "the name of the city" )
  ( "shm", boost::program_options::value< std::string > (), "shared memory segment name" )
  ( "node2gps", boost::program_options::value< std::string > (), "node2gps file name" )
  ( "node2way", boost::program_options::value< std::string > (), "node2way file name" )
 ;

  boost::program_options::variables_map vm;
  boost::program_options::store ( boost::program_options::parse_command_line ( argc, argv, desc ), vm );
  boost::program_options::notify ( vm );

  if ( vm.count ( "version" ) )
    {
      std::cout << "Robocar City Emulator and Robocar World Championship, City Server" << std::endl
                << "Copyright (C) 2014, 2015 Norbert Bátfai\n" << std::endl
                << "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>" << std::endl
                << "This is free software: you are free to change and redistribute it." << std::endl
                << "There is NO WARRANTY, to the extent permitted by law." << std::endl;
      return 0;
    }

  if ( vm.count ( "help" ) )
    {
      std::cout << "Robocar City Emulator and Robocar World Championship home page: https://code.google.com/p/robocar-emulator/" << std::endl;
      std::cout << desc << std::endl;
      std::cout << "Please report bugs to: [email protected]" << std::endl;
      return 0;
    }

  std::string osm_input;
  if ( vm.count ( "osm" ) )
    osm_input.assign ( vm["osm"].as < std::string > () );
  else
    osm_input.assign ( "../debrecen.osm" );

  std::string node2gps_output;
  if ( vm.count ( "node2gps" ) )
    node2gps_output.assign ( vm["node2gps"].as < std::string > () );
  else
    node2gps_output.assign ( "../lmap.txt" );

  std::string node2way_output;
  if ( vm.count ( "node2way" ) )
    node2way_output.assign ( vm["node2way"].as < std::string > () );
  else
    node2way_output.assign ( "../lmap.txt" );  
  
  std::string city;
  if ( vm.count ( "city" ) )
    city.assign ( vm["city"].as < std::string > () );
  else
    city.assign ( "Debrecen" );

  std::string shm;
  if ( vm.count ( "shm" ) )
    shm.assign ( vm["shm"].as < std::string > () );
  else
    shm.assign ( "JustineSharedMemory" );

  // Do not remove this copyright notice!
  std::cout << "Robocar City Emulator and Robocar World Championship, City Server" << std::endl
            << "Copyright (C) 2014, 2015 Norbert Bátfai" << std::endl
            << "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>" << std::endl
            << "This is free software: you are free to change and redistribute it." << std::endl
            << "There is NO WARRANTY, to the extent permitted by law." << std::endl;

  std::cout << city << " is... " << std::flush;
  try
    {

      if ( vm.count ( "node2gps" ) )
        justine::robocar::SmartCity smartCity ( osm_input.c_str(), shm.c_str(), node2gps_output.c_str(), 0 );
      else if ( vm.count ( "node2way" ) )
        justine::robocar::SmartCity smartCity ( osm_input.c_str(), shm.c_str(), node2way_output.c_str(), 1 );
      else
        justine::robocar::SmartCity smartCity ( osm_input.c_str(), shm.c_str() );

      std::cout << "ready."<<  std::endl;
      for ( ;; );

    }
  catch ( std::exception &err )
    {

      std::cout << "SmartCity cannot be built for "+city << std::endl;
      std::cout << err.what() <<std::endl;

    }

}
Exemple #21
0
int main(int argc, char *argv[] )
{

  // Default arguments
  std::string outbase = "canvas";
  std::string outname = outbase + ".root";
  std::string pdfname = outbase + ".pdf";
  bool makePdf = false;
  makeGraphic = false;
  std::string infileName;
  std::vector<std::string> inFileVector ; inFileVector.clear() ; 

  //--- Get parameters from command line ---//
  boost::program_options::options_description desc(
	      "Available options for multiPlotter") ;
  desc.add_options()
    ("help,h","Print this help message")
    ("infile,i",   boost::program_options::value<std::string>(),
     //     "Input file name (Default is validation.root)") 
     "Input file name") 
    ("outfile,o",  boost::program_options::value<std::string>(),
     "Sets output files to <outfile>.root/.pdf (default is canvas)")
    ("pdf,p",
     "Make a PDF file")
    ("graphic,g",
     "makes a gif file for each TCanvas");

  std::string usage = "\nSample multiPlotter usage::\n" ; 
  usage += "\"multiPlotter -o validation-canvas -i validation.root\"\n " ; 
  usage += "\t input= validation.root\n" ;
  usage += "\t output= validation-canvas.root\n" ;
  usage += "\"multiPlotter -g -p -o validation-canvas -i \"validation_01.root validation_02.root\" \"\n" ;
  usage += "\t input= validation_01.root AND validation_02.root\n" ;
  usage += "\t output= validation-canvas.root\n" ;
  usage += "\t         validation-canvas.pdf\n" ;
  usage += "\t         gif files in validation-canvas/ \n\t\t\t (a directory tree which has the same \n\t\t\t directory structure as validation-canvas.root\n" ;
  usage += "\n" ; 

  boost::program_options::positional_options_description pos ; 
  boost::program_options::variables_map vmap ;
  
  try {
    boost::program_options::store(boost::program_options::command_line_parser(argc,argv).
				  options(desc).positional(pos).run(), vmap) ; 
  } catch (boost::program_options::error const& x) {
    std::cerr << "Unable to parse options:\n"
	      << x.what() << "\n\n" ;
    std::cerr << desc << usage << std::endl ;
    return 1 ; 
  }
  
  boost::program_options::notify(vmap) ; 
  if (vmap.count("help")) {
    std::cout << desc << usage <<  std::endl ;
    return 1 ;
  }
  if (vmap.count("outfile")) {
    outbase = vmap["outfile"].as<std::string>() ; 
    outname = outbase + ".root" ;
    pdfname = outbase + ".pdf" ;
  }
  if (vmap.count("pdf")) {
    makePdf = true ; 
  } 
  if (vmap.count("graphic")) {
    makeGraphic = true ; 
  } 
  if (vmap.count("infile")) {
    infileName = vmap["infile"].as<std::string>() ;
    /*
    std::ifstream inFile(infileName.c_str()) ;
    if (inFile.is_open()) { //--- input files listed in a file ---//
      while ( !inFile.eof() ) {
	std::string skipped ;
	getline(inFile,skipped) ; 
	inFileVector.push_back( skipped ) ;
      }
    } else 
    */
    { //--- Assume the file is a space-separated list of files -//
      size_t strStart = 0 ; 
      for (size_t itr=infileName.find(" ",0); itr!=std::string::npos;
	   itr=infileName.find(" ",itr)) {
	std::string skipped = infileName.substr(strStart,(itr-strStart)) ; 
	itr++ ; strStart = itr ; 
	inFileVector.push_back( skipped ) ;
      }
      //--- Fill the last entry ---//
      inFileVector.push_back( infileName.substr(strStart,infileName.length()) ); 
    }
  }
  else {
    std::cout << " *** No input file given: please define one " << std::endl;
    return 0;
  }

  TDirectory *target = TFile::Open(TString(outname),"RECREATE");
  
  baseName = new TString(outbase);
  baseName->Append("/");
  
  TList *sourcelist = new TList();  
  for (std::vector<std::string>::size_type i = 0; i < inFileVector.size(); i++) {
    std::cout << inFileVector[i] << " " << std::endl;
    sourcelist->Add(TFile::Open(TString(inFileVector[i])));
  }

  TCanvas* c1 = new TCanvas("c1") ;
  pdf = 0 ;
  if (makePdf) pdf = new TPDF(TString(pdfname)) ;
  //  int pageNumber = 2 ;
  // double titleSize = 0.050 ; 
  
  gROOT->SetStyle("Plain") ; 
  gStyle->SetPalette(1) ; 
  //gStyle->SetOptStat(111111) ;
  gStyle->SetOptStat(0) ;
  c1->UseCurrentStyle() ; 
  gROOT->ForceStyle() ;
  
  drawLoop(target,sourcelist,c1);
  
  if (makePdf) pdf->Close();
  target->Close();
  return 0;
}
Exemple #22
0
/***********************************************************************
 * Main code + dispatcher
 **********************************************************************/
int UHD_SAFE_MAIN(int argc, char *argv[]){
    uhd::set_thread_priority_safe();

    //variables to be set by po
    std::string args;
    std::string rx_subdev, tx_subdev;
    double duration;
    double rx_rate, tx_rate;
    std::string rx_otw, tx_otw;
    std::string rx_cpu, tx_cpu;
    std::string mode, ref, pps;
    std::string channel_list, rx_channel_list, tx_channel_list;
    bool random_nsamps = false;
    std::atomic<bool> burst_timer_elapsed(false);
    size_t overrun_threshold, underrun_threshold, drop_threshold, seq_threshold;

    //setup the program options
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "help message")
        ("args", po::value<std::string>(&args)->default_value(""), "single uhd device address args")
        ("duration", po::value<double>(&duration)->default_value(10.0), "duration for the test in seconds")
        ("rx_subdev", po::value<std::string>(&rx_subdev), "specify the device subdev for RX")
        ("tx_subdev", po::value<std::string>(&tx_subdev), "specify the device subdev for TX")
        ("rx_rate", po::value<double>(&rx_rate), "specify to perform a RX rate test (sps)")
        ("tx_rate", po::value<double>(&tx_rate), "specify to perform a TX rate test (sps)")
        ("rx_otw", po::value<std::string>(&rx_otw)->default_value("sc16"), "specify the over-the-wire sample mode for RX")
        ("tx_otw", po::value<std::string>(&tx_otw)->default_value("sc16"), "specify the over-the-wire sample mode for TX")
        ("rx_cpu", po::value<std::string>(&rx_cpu)->default_value("fc32"), "specify the host/cpu sample mode for RX")
        ("tx_cpu", po::value<std::string>(&tx_cpu)->default_value("fc32"), "specify the host/cpu sample mode for TX")
        ("ref", po::value<std::string>(&ref), "clock reference (internal, external, mimo, gpsdo)")
        ("pps", po::value<std::string>(&pps), "PPS source (internal, external, mimo, gpsdo)")
        ("mode", po::value<std::string>(&mode), "DEPRECATED - use \"ref\" and \"pps\" instead (none, mimo)")
        ("random", "Run with random values of samples in send() and recv() to stress-test the I/O.")
        ("channels", po::value<std::string>(&channel_list)->default_value("0"), "which channel(s) to use (specify \"0\", \"1\", \"0,1\", etc)")
        ("rx_channels", po::value<std::string>(&rx_channel_list), "which RX channel(s) to use (specify \"0\", \"1\", \"0,1\", etc)")
        ("tx_channels", po::value<std::string>(&tx_channel_list), "which TX channel(s) to use (specify \"0\", \"1\", \"0,1\", etc)")
        ("overrun-threshold", po::value<size_t>(&overrun_threshold),
         "Number of overruns (O) which will declare the benchmark a failure.")
        ("underrun-threshold", po::value<size_t>(&underrun_threshold),
         "Number of underruns (U) which will declare the benchmark a failure.")
        ("drop-threshold", po::value<size_t>(&drop_threshold),
         "Number of dropped packets (D) which will declare the benchmark a failure.")
        ("seq-threshold", po::value<size_t>(&seq_threshold),
         "Number of dropped packets (D) which will declare the benchmark a failure.")
    ;
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    //print the help message
    if (vm.count("help") or (vm.count("rx_rate") + vm.count("tx_rate")) == 0){
        std::cout << boost::format("UHD Benchmark Rate %s") % desc << std::endl;
        std::cout <<
        "    Specify --rx_rate for a receive-only test.\n"
        "    Specify --tx_rate for a transmit-only test.\n"
        "    Specify both options for a full-duplex test.\n"
        << std::endl;
        return ~0;
    }

    // Random number of samples?
    if (vm.count("random")) {
        std::cout << "Using random number of samples in send() and recv() calls." << std::endl;
        random_nsamps = true;
    }

    if (vm.count("mode")) {
        if (vm.count("pps") or vm.count("ref")) {
            std::cout << "ERROR: The \"mode\" parameter cannot be used with the \"ref\" and \"pps\" parameters.\n" << std::endl;
            return -1;
        } else if (mode == "mimo") {
            ref = pps = "mimo";
            std::cout << "The use of the \"mode\" parameter is deprecated.  Please use \"ref\" and \"pps\" parameters instead\n" << std::endl;
        }
    }

    //create a usrp device
    std::cout << std::endl;
    uhd::device_addrs_t device_addrs = uhd::device::find(args, uhd::device::USRP);
    if (not device_addrs.empty() and device_addrs.at(0).get("type", "") == "usrp1"){
        std::cerr << "*** Warning! ***" << std::endl;
        std::cerr << "Benchmark results will be inaccurate on USRP1 due to insufficient features.\n" << std::endl;
    }
    boost::posix_time::ptime start_time(boost::posix_time::microsec_clock::local_time());
    std::cout << boost::format("[%s] Creating the usrp device with: %s...") % NOW() % args << std::endl;
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(args);

    //always select the subdevice first, the channel mapping affects the other settings
    if (vm.count("rx_subdev")) {
        usrp->set_rx_subdev_spec(rx_subdev);
    }
    if (vm.count("tx_subdev")) {
        usrp->set_tx_subdev_spec(tx_subdev);
    }

    std::cout << boost::format("Using Device: %s") % usrp->get_pp_string() << std::endl;
    int num_mboards = usrp->get_num_mboards();

    boost::thread_group thread_group;

    if(vm.count("ref"))
    {
        if (ref == "mimo")
        {
            if (num_mboards != 2) {
                std::cerr << "ERROR: ref = \"mimo\" implies 2 motherboards; your system has " << num_mboards << " boards" << std::endl;
                return -1;
            }
            usrp->set_clock_source("mimo",1);
        } else {
            usrp->set_clock_source(ref);
        }

        if(ref != "internal") {
            std::cout << "Now confirming lock on clock signals..." << std::endl;
            bool is_locked = false;
            auto end_time =
                boost::get_system_time() +
                boost::posix_time::milliseconds(CLOCK_TIMEOUT);
            for (int i = 0; i < num_mboards; i++) {
                if (ref == "mimo" and i == 0) continue;
                while((is_locked = usrp->get_mboard_sensor("ref_locked",i).to_bool()) == false and
                            boost::get_system_time() < end_time )
                {
                    std::this_thread::sleep_for(std::chrono::milliseconds(1));
                }
                if (is_locked == false) {
                    std::cerr << "ERROR: Unable to confirm clock signal locked on board:" << i <<  std::endl;
                    return -1;
                }
                is_locked = false;
            }
        }
    }

    if(vm.count("pps"))
    {
       if(pps == "mimo")
       {
           if (num_mboards != 2) {
               std::cerr << "ERROR: ref = \"mimo\" implies 2 motherboards; your system has " << num_mboards << " boards" << std::endl;
               return -1;
           }
           //make mboard 1 a slave over the MIMO Cable
           usrp->set_time_source("mimo", 1);
       } else {
           usrp->set_time_source(pps);
       }
    }

    //check that the device has sufficient RX and TX channels available
    std::vector<std::string> channel_strings;
    std::vector<size_t> rx_channel_nums;
    if (vm.count("rx_rate")) {
        if (!vm.count("rx_channels")) {
            rx_channel_list = channel_list;
        }

        boost::split(channel_strings, rx_channel_list, boost::is_any_of("\"',"));
        for (size_t ch = 0; ch < channel_strings.size(); ch++) {
            size_t chan = std::stoul(channel_strings[ch]);
            if (chan >= usrp->get_rx_num_channels()) {
                throw std::runtime_error("Invalid channel(s) specified.");
            } else {
                rx_channel_nums.push_back(std::stoul(channel_strings[ch]));
            }
        }
    }

    std::vector<size_t> tx_channel_nums;
    if (vm.count("tx_rate")) {
        if (!vm.count("tx_channels")) {
            tx_channel_list = channel_list;
        }

        boost::split(channel_strings, tx_channel_list, boost::is_any_of("\"',"));
        for (size_t ch = 0; ch < channel_strings.size(); ch++) {
            size_t chan = std::stoul(channel_strings[ch]);
            if (chan >= usrp->get_tx_num_channels()) {
                throw std::runtime_error("Invalid channel(s) specified.");
            } else {
                tx_channel_nums.push_back(std::stoul(channel_strings[ch]));
            }
        }
    }

    std::cout << boost::format("[%s] Setting device timestamp to 0...") % NOW() << std::endl;
    if (pps == "mimo" or ref == "mimo") {
        // only set the master's time, the slave's is automatically sync'd
        usrp->set_time_now(uhd::time_spec_t(0.0), 0);
        // ensure that the setter has completed
        usrp->get_time_now();
        // wait for the time to sync
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    } else if (rx_channel_nums.size() > 1 or tx_channel_nums.size() > 1) {
        usrp->set_time_unknown_pps(uhd::time_spec_t(0.0));
    } else {
        usrp->set_time_now(0.0);
    }

    //spawn the receive test thread
    if (vm.count("rx_rate")){
        usrp->set_rx_rate(rx_rate);
        //create a receive streamer
        uhd::stream_args_t stream_args(rx_cpu, rx_otw);
        stream_args.channels = rx_channel_nums;
        uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);
        auto rx_thread = thread_group.create_thread([=, &burst_timer_elapsed](){
            benchmark_rx_rate(
                usrp,
                rx_cpu,
                rx_stream,
                random_nsamps,
                start_time,
                burst_timer_elapsed
            );
        });
        uhd::set_thread_name(rx_thread, "bmark_rx_stream");
    }

    //spawn the transmit test thread
    if (vm.count("tx_rate")){
        usrp->set_tx_rate(tx_rate);
        //create a transmit streamer
        uhd::stream_args_t stream_args(tx_cpu, tx_otw);
        stream_args.channels = tx_channel_nums;
        uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args);
        auto tx_thread = thread_group.create_thread([=, &burst_timer_elapsed](){
            benchmark_tx_rate(
                usrp,
                tx_cpu,
                tx_stream,
                burst_timer_elapsed,
                start_time,
                random_nsamps
            );
        });
        uhd::set_thread_name(tx_thread, "bmark_tx_stream");
        auto tx_async_thread = thread_group.create_thread([=, &burst_timer_elapsed](){
            benchmark_tx_rate_async_helper(
                tx_stream,
                start_time,
                burst_timer_elapsed
            );
        });
        uhd::set_thread_name(tx_async_thread, "bmark_tx_helper");
    }

    //sleep for the required duration
    const bool wait_for_multichan =
        (rx_channel_nums.size() <= 1 and tx_channel_nums.size() <= 1);
    const int64_t secs =
        int64_t(duration + (wait_for_multichan ? 0 : INIT_DELAY * 1000));
    const int64_t usecs = int64_t((duration - secs)*1e6);
    std::this_thread::sleep_for(
        std::chrono::seconds(secs) +
        std::chrono::microseconds(usecs)
    );

    //interrupt and join the threads
    burst_timer_elapsed = true;
    thread_group.join_all();

    std::cout << "[" << NOW() << "] Benchmark complete." << std::endl << std::endl;

    //print summary
    const std::string threshold_err(" ERROR: Exceeds threshold!");
    const bool overrun_threshold_err =
        vm.count("overrun-threshold") and
        num_overruns > overrun_threshold;
    const bool underrun_threshold_err =
        vm.count("underrun-threshold") and
        num_underruns > underrun_threshold;
    const bool drop_threshold_err =
        vm.count("drop-threshold") and
        num_seqrx_errors > drop_threshold;
    const bool seq_threshold_err =
        vm.count("seq-threshold") and
        num_seq_errors > seq_threshold;
    std::cout << std::endl
        << boost::format(
                "Benchmark rate summary:\n"
                "  Num received samples:     %u\n"
                "  Num dropped samples:      %u\n"
                "  Num overruns detected:    %u\n"
                "  Num transmitted samples:  %u\n"
                "  Num sequence errors (Tx): %u\n"
                "  Num sequence errors (Rx): %u\n"
                "  Num underruns detected:   %u\n"
                "  Num late commands:        %u\n"
                "  Num timeouts (Tx):        %u\n"
                "  Num timeouts (Rx):        %u\n"
            ) % num_rx_samps
              % num_dropped_samps
              % num_overruns
              % num_tx_samps
              % num_seq_errors
              % num_seqrx_errors
              % num_underruns
              % num_late_commands
              % num_timeouts_tx
              % num_timeouts_rx
        << std::endl;
    //finished
    std::cout << std::endl << "Done!" << std::endl << std::endl;

    if (overrun_threshold_err
            || underrun_threshold_err
            || drop_threshold_err
            || seq_threshold_err) {
        std::cout << "The following error thresholds were exceeded:\n";
        if (overrun_threshold_err) {
            std::cout
                << boost::format("  * Overruns (%d/%d)")
                   % num_overruns
                   % overrun_threshold
                << std::endl;
        }
        if (underrun_threshold_err) {
            std::cout
                << boost::format("  * Underruns (%d/%d)")
                   % num_underruns
                   % underrun_threshold
                << std::endl;
        }
        if (drop_threshold_err) {
            std::cout
                << boost::format("  * Dropped packets (RX) (%d/%d)")
                   % num_seqrx_errors
                   % drop_threshold
                << std::endl;
        }
        if (seq_threshold_err) {
            std::cout
                << boost::format("  * Dropped packets (TX) (%d/%d)")
                   % num_seq_errors
                   % seq_threshold
                << std::endl;
        }
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
int main(int ac, char* av[])
{	
	int use_video;					// Use camera or directory
	std::string publisher_mode;		// (tcp://*:8666) 
	std::string image_dir;			// Image directory used if input is directory
	std::string image_extension;	// Image type (.jpg, .tif, .bmp, .png)
	int debugMode;					// Display image 
	int equalizeHist;				// Use the histogram equalization
	std::string ROI;				// ROI applied to the image sent

	try
	{
		// Parse program options
		// Parse program options...
		po::options_description desc("Allowed options");
		desc.add_options()
            ("help,h", "produce help message")
			("Publisher_mode,p",  po::value<std::string>(&publisher_mode)->default_value("tcp://*:8666"), "UDP server port")
			("video,v",  po::value<int>(&use_video)->default_value(0), "Use camera flag") 
			("debug,g",  po::value<int>(&debugMode)->default_value(0), "Debug mode") 
			("equalize,q",  po::value<int>(&equalizeHist)->default_value(0), "Equalize histogram")
			("ROI,r", po::value<std::string>(&ROI)->default_value(""),"Apply ROI on image sent.")
			("directory,d", po::value<std::string>(&image_dir)->default_value("."),"Image directory.")
			("extension,e", po::value<std::string>(&image_extension)->default_value(".jpg"),"Image extension.")
        ;
		po::variables_map vm;        
        po::store(po::parse_command_line(ac, av, desc), vm);
        po::notify(vm);

		if (vm.count("help")) 
		{
			std::cout << desc << std::endl;
            return 1;
        }
		if (vm.count("video")) 
		{            
			std::cout << "Video mode set to " << vm["video"].as<int>() << std::endl;
        }
		if (vm.count("Publisher_mode")) 
		{            
			std::cout << "Publisher mode set to " << vm["Publisher_mode"].as<std::string>() << std::endl;
        }
		if (vm.count("directory"))
        {            
			std::cout << "Image directory: " << vm["directory"].as<std::string>() << std::endl;			
        }
		if (vm.count("extension"))
        {            
			std::cout << "Image extension: " << vm["extension"].as<std::string>() << std::endl;			
        }

		// Initialize ImageFactory
		ImageFactory imFactory(use_video,image_dir,image_extension,debugMode,ROI,equalizeHist);

		// Initialize ImageGather (prepare images to be sent)
		ImageGather  imgGather(imFactory);
		
		// Initialize ZMQ
		zmq::context_t context (1);

		// Get socket to publish 
		zmq::socket_t publisher (context, ZMQ_PUB);

		// Bind the socket to some port (TCP,or IPC)
		publisher.bind(publisher_mode.c_str());			
		
		while(1)
		{						
			// Get image to be sent
			GenericImage image;
			imgGather.prepareImage(image);						
			
			// Create message content
			boost::format fmter("%05d ");									// Format string 5 = 000005
			fmter % image.getHeader().length();
			std::string headerSize = fmter.str();
			std::string completeHeader = headerSize + image.getHeader();			

			// Create a message			
			zmq::message_t message(completeHeader.length() + image.getSize() + 1);			

			// Copy image header
			memcpy((char*) message.data(), completeHeader.c_str(), completeHeader.length());	
			
			// Copy image content
			char *postHeader = (char*) message.data();
			postHeader += completeHeader.length() + 1;			
			memcpy((char*)postHeader,image.getImageBuffer(), image.getSize()); 
			
			// Broadcast this message
			publisher.send(message);			
		}
	}
	catch(std::exception &e)
	{		
		std::cerr << e.what() << std::endl;
	}
	std::cout << "Image broadcast closing" << std::endl;

	return 0;
}
void Texture2D::InternalConstruct(ID3D11Device* d3dDevice,
                                  int width, int height, DXGI_FORMAT format,
                                  UINT bindFlags, int mipLevels, int arraySize,
                                  int sampleCount, int sampleQuality,
                                  D3D11_RTV_DIMENSION rtvDimension,
                                  D3D11_UAV_DIMENSION uavDimension,
                                  D3D11_SRV_DIMENSION srvDimension)
{
    // Initalize
    mShaderResource = 0;

    CD3D11_TEXTURE2D_DESC desc(
        format,
        width, height, arraySize, mipLevels,
        bindFlags,
        D3D11_USAGE_DEFAULT, 0,
        sampleCount, sampleQuality,
        // If they request mipmap levels, it's nice to be able to autogenerate them.
        (mipLevels != 1 ? D3D11_RESOURCE_MISC_GENERATE_MIPS : 0));

    d3dDevice->CreateTexture2D(&desc, 0, &mTexture);

    // Update with actual mip levels, etc.
    mTexture->GetDesc(&desc);

    if (bindFlags & D3D11_BIND_RENDER_TARGET) {
        for (int i = 0; i < arraySize; ++i) {
            CD3D11_RENDER_TARGET_VIEW_DESC rtvDesc(
                rtvDimension,
                format,
                0,          // Mips
                i, 1        // Array
            );

            ID3D11RenderTargetView* renderTargetView;
            d3dDevice->CreateRenderTargetView(mTexture, &rtvDesc, &renderTargetView);
            mRenderTargetElements.push_back(renderTargetView);
        }
    }

    if (bindFlags & D3D11_BIND_UNORDERED_ACCESS) {
        // UAV's can't point to multisampled resources!
        assert(uavDimension != D3D11_UAV_DIMENSION_UNKNOWN);

        for (int i = 0; i < arraySize; ++i) {
            CD3D11_UNORDERED_ACCESS_VIEW_DESC uavDesc(
                uavDimension,
                format,
                0,          // Mips
                i, 1        // Array
            );

            ID3D11UnorderedAccessView* unorderedAccessView;
            d3dDevice->CreateUnorderedAccessView(mTexture, &uavDesc, &unorderedAccessView);
            mUnorderedAccessElements.push_back(unorderedAccessView);
        }
    }

    if (bindFlags & D3D11_BIND_SHADER_RESOURCE) {
        // Whole resource
        CD3D11_SHADER_RESOURCE_VIEW_DESC srvDesc(
            srvDimension,
            format,
            0, desc.MipLevels,  // Mips
            0, desc.ArraySize   // Array
        );        

        d3dDevice->CreateShaderResourceView(mTexture, &srvDesc, &mShaderResource);

        // Single elements
        for (int i = 0; i < arraySize; ++i) {
            CD3D11_SHADER_RESOURCE_VIEW_DESC srvElementDesc(
                srvDimension,
                format,
                0, 1,  // Mips
                i, 1   // Array
            );

            ID3D11ShaderResourceView* shaderResourceView;
            d3dDevice->CreateShaderResourceView(mTexture, &srvElementDesc, &shaderResourceView);
            mShaderResourceElements.push_back(shaderResourceView);
        }
    }
}
Exemple #25
0
NSCAPI::nagiosReturn CheckWMI::commandLineExec(const std::string &command, const std::list<std::string> &arguments, std::string &result) {
	try {
		if (command == "wmi" || command == "help" || command.empty()) {

			namespace po = boost::program_options;

			std::string query, ns, user, password, list_cls, list_inst;
			std::string computer;
			bool simple;
			int limit = -1;
			po::options_description desc("Allowed options");
			desc.add_options()
				("help,h", "Show help screen")
				("select,s", po::value<std::string>(&query), "Execute a query")
				("simple", "Use simple format")
				("list-classes", po::value<std::string>(&list_cls)->implicit_value(""), "list all classes of a given type")
				("list-instances", po::value<std::string>(&list_inst), "list all instances of a given type")
				("list-ns", "list all name spaces")
				("list-all-ns", "list all name spaces recursively")
				("limit,l", po::value<int>(&limit), "Limit number of rows")
				("namespace,n", po::value<std::string>(&ns)->default_value("root\\cimv2"), "Namespace")
				("computer,c", po::value<std::string>(&computer), "A remote computer to connect to ")
				("user,u", po::value<std::string>(&user), "The user for the remote computer")
				("password,p", po::value<std::string>(&password), "The password for the remote computer")
				;

			boost::program_options::variables_map vm;

			if (command == "help") {
				std::stringstream ss;
				ss << "wmi Command line syntax:" << std::endl;
				ss << desc;
				result = ss.str();
				return NSCAPI::isSuccess;
			}

			std::vector<std::string> args(arguments.begin(), arguments.end());
			po::parsed_options parsed = po::basic_command_line_parser<char>(args).options(desc).run();
			po::store(parsed, vm);
			po::notify(vm);

			if (vm.count("help") || (vm.count("select") == 0 && vm.count("list-classes") == 0 && vm.count("list-instances") == 0 && vm.count("list-ns") == 0 && vm.count("list-all-ns") == 0)) {
				std::stringstream ss;
				ss << "CheckWMI Command line syntax:" << std::endl;
				ss << desc;
				result = ss.str();
				return NSCAPI::isSuccess;
			}
			simple = vm.count("simple") > 0;

			ns = build_namespace(ns, computer);

			if (vm.count("select")) {
				row_type headers;
				std::vector<std::size_t> widths;
				std::size_t count = 0;
				try {
					wmi_impl::query wmiQuery(query, ns, user, password);
					std::list<std::string> cols = wmiQuery.get_columns();
					count = cols.size();
					BOOST_FOREACH(const std::string &col, cols) {
						headers.push_back(col);
						widths.push_back(col.size());
					}
					result = render(headers, widths, wmiQuery.execute());
					return NSCAPI::isSuccess;
				} catch (const wmi_impl::wmi_exception &e) {
					result += "ERROR: " + e.reason();
					return NSCAPI::hasFailed;
				}
			} else if (vm.count("list-classes")) {
Exemple #26
0
int
main (int argc, char ** argv)
{
    typedef pcl::PointXYZRGB PointT;

    std::string test_dir;
    bool visualize = false;
    double chop_z = std::numeric_limits<double>::max();

    google::InitGoogleLogging(argv[0]);

    po::options_description desc("Single-View Object Instance Recognizer\n======================================\n**Allowed options");
    desc.add_options()
        ("help,h", "produce help message")
        ("test_dir,t", po::value<std::string>(&test_dir)->required(), "Directory with test scenes stored as point clouds (.pcd). The camera pose is taken directly from the pcd header fields \"sensor_orientation_\" and \"sensor_origin_\" (if the test directory contains subdirectories, each subdirectory is considered as seperate sequence for multiview recognition)")
        ("visualize,v", po::bool_switch(&visualize), "visualize recognition results")
        ("chop_z,z", po::value<double>(&chop_z)->default_value(chop_z, boost::str(boost::format("%.2e") % chop_z) ), "points with z-component higher than chop_z_ will be ignored (low chop_z reduces computation time and false positives (noise increase with z)")
   ;
    po::variables_map vm;
    po::parsed_options parsed = po::command_line_parser(argc, argv).options(desc).allow_unregistered().run();
    std::vector<std::string> to_pass_further = po::collect_unrecognized(parsed.options, po::include_positional);
    po::store(parsed, vm);
    if (vm.count("help")) { std::cout << desc << std::endl; to_pass_further.push_back("-h"); }
    try { po::notify(vm); }
    catch(std::exception& e) { std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl;  }

    v4r::MultiRecognitionPipeline<PointT> r(to_pass_further);

    // ----------- TEST ----------
    std::vector< std::string> sub_folder_names = v4r::io::getFoldersInDirectory( test_dir );
    if(sub_folder_names.empty())
        sub_folder_names.push_back("");

    for (const std::string &sub_folder_name : sub_folder_names)
    {
        const std::string sequence_path = test_dir + "/" + sub_folder_name;

        std::vector< std::string > views = v4r::io::getFilesInDirectory(sequence_path, ".*.pcd", false);
        for (size_t v_id=0; v_id<views.size(); v_id++)
        {
            const std::string fn = sequence_path + "/" + views[ v_id ];

            LOG(INFO) << "Recognizing file " << fn;
            typename pcl::PointCloud<PointT>::Ptr cloud(new pcl::PointCloud<PointT>());
            pcl::io::loadPCDFile(fn, *cloud);

            //reset view point - otherwise this messes up PCL's visualization (this does not affect recognition results)
            cloud->sensor_orientation_ = Eigen::Quaternionf::Identity();
            cloud->sensor_origin_ = Eigen::Vector4f::Zero(4);

//            if( chop_z > 0)
//            {
//                pcl::PassThrough<PointT> pass;
//                pass.setFilterLimits ( 0.f, chop_z );
//                pass.setFilterFieldName ("z");
//                pass.setInputCloud (cloud);
//                pass.setKeepOrganized (true);
//                pass.filter (*cloud);
//            }

            r.setInputCloud (cloud);
            r.recognize();

            std::vector<typename v4r::ObjectHypothesis<PointT>::Ptr > ohs = r.getVerifiedHypotheses();


//            std::vector<ModelTPtr> verified_models = r.getVerifiedModels();
//            std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f> > transforms_verified;
//            transforms_verified = r.getVerifiedTransforms();

            if (visualize)
                r.visualize();

            for(size_t m_id=0; m_id<ohs.size(); m_id++)
            {
                std::cout << "********************" << ohs[m_id]->model_->id_ << std::endl
                          << ohs[m_id]->transform_ << std::endl << std::endl;
            }
        }
    }
}
Exemple #27
0
int main(int argc , char* argv[]){
		
		//Program Options

	po::options_description desc("Allowed Options");
	desc.add_options()
		 ("help,h", "Produce this help message")
		 ("startwl,s",po::value<double>(),"Set the start Wavelength for the Analysis")
		 ("stopwl,p",po::value<double>(),"Set the stop Wavelength for the Analysis")
		 ("non-interactive,n","Runs the program in Noninteractive mode. It quits when it's finished")
		 ("version,v","Prints Version")
	;
		 
	po::variables_map vm;
		 po::store(po::parse_command_line(argc,argv,desc),vm);
		 po::notify(vm);
	if (vm.count("help")) {
		std::cout << desc<< std::endl;
		return 3;
	}
	if (vm.count("version")) {
		std::cout << "VCSEL Laser Analysis Version " << _VERSION << std::endl;
		std::cout << "Using ROOT version " << _ROOT_VERSION << " and Boost version " << _BOOST_VERSION << std::endl;
		return 0;
	}
	
	if (argc < 4) {
		std::cout << desc;
		return 2;
	}	
	double startwl, stopwl;
	startwl = 842.;
	stopwl = 860.;
	bool run = true;
	if (vm.count("startwl")) {
		startwl = vm["startwl"].as<double>();
		NUM_ARGS +=2;
	}
	if (vm.count("stopwl")) {
		double tmp =  vm["stopwl"].as<double>();
		stopwl =tmp;
		NUM_ARGS +=2;
	}
	if (vm.count("non-interactive")) {
		run = false;
		NUM_ARGS++;
	}
	
	
	//checking filetypes must be txt, csv or CSV
	if (!check_extensions(argc, argv)) {
		return 1;
	}
	std::cout <<"startwl: "<< startwl << '\t' << "stopwl: " << stopwl << std::endl;
	
	Double_t max = -210;
	Double_t maxwl = 0;
	int _argc = argc;
	TApplication *t = new TApplication("big",&_argc,argv);
	std::cout << "Running with boost and ROOT" <<std::endl;
	std::vector<double> _x,_y;
	Double_t x[LINES], y[LINES], _inta[LINES], _intb[LINES]; 
	
	Double_t *cmp_int = new Double_t[argc];
	Double_t *argc_ary = new Double_t[argc];
	Double_t *cmp_int_root = new Double_t[argc];
	Double_t *asymmety_ary = new Double_t[argc];
	Double_t *width_ary = new Double_t [argc];
	

	
	TGraph2D *gr = new TGraph2D(LINES*(argc-1));
		//Setting up canvas for plot of all sectrums (is it called spectrums? ;) )
	TCanvas *c1 = new TCanvas("All Plots","All Plots",10,10,3000,1500);
	TH1F *integral_hist = new TH1F("Asymmerty", "Asymmetry", 100,0, 100);
	

	if(!(argc % ROWS)){
		c1->Divide(argc/ROWS,ROWS);
		
	}else{
		c1->Divide(argc/ROWS+(argc %ROWS -1),ROWS);
	}
	
	for (Int_t i = NUM_ARGS +1; i < argc ; i++){
		try{ 
			
			max = -211;
			maxwl = 0;
			argc_ary[i] = i-NUM_ARGS;
			
			std::ifstream in;
			in.seekg(0, std::ios::beg);
				// voodoo keep this;
			char **arg1 = t->Argv() ;
			std::string tmp = arg1[i];
			in.open(tmp.c_str());
			
			std::cout<< "file: " << tmp << std::endl;
			std::string line;
			int cline = 0;
			std::vector<double> a,b, inta, intb;
			
				//reading file
			
			while(getline(in,line)){
				read_file(line, a, b, inta, intb);
				cline++;
			}
			
			if (cline < LINES){
				for(int i = cline ; i < LINES ; i++){
					a.push_back(100);
					b.push_back(-70);
				}
			}
			std::cout<< "\n\ncline: " << cline<< std::endl; 
			cline =(cline > LINES) ? LINES :cline;
			
			for(Int_t j = 0; j <LINES ;j++){
				x[j] = a[j];
				y[j] = b[j];
				_inta[j] = inta[j];
				_intb[j]= (intb[j] < 0)? 0:intb[j];
			}
			
			
			
			double s_integral = 0;
			
			std::cout <<"size of int " <<  intb.size()<< std::endl;
			for (size_t it = 0; it < intb.size() - 1; it++){
				double y_val = (intb[it]+intb[it+1])/2;
				assert (y_val >= 0);
				double area = 0.002*y_val;
				if(area > 0 )
					s_integral += area;
			}
			
			
			
			
			std::cout << "Simpson integral: " <<s_integral <<std::endl;
			integral_hist->Fill(s_integral);
			cmp_int[i] = s_integral;
			Int_t lines = (Int_t)intb.size();
			TGraph *r_integral = new TGraph(lines, _inta, _intb);
			
			std::cout << "ROOT integral: " << r_integral->Integral() << std::endl;
			cmp_int_root[i] = r_integral->Integral();
			
				//expanding
				//expand(y, THRS_EXPAND, RATIO_EXPAND, LINES);
			
			
				//Filling TGraph2D
			
			for(Int_t j = 0; j <LINES ; j++){
				if (y[j] > max){
					max = y[j];
					maxwl = x[j];
				}
				gr->SetPoint(j+i*LINES, x[j],i,y[j]);
			}
			
			
			in.seekg(0, std::ios::beg);
			in.close();
			
				//Plotting each spectrum
			
			TGraph *_gr = new TGraph(LINES,x,y);
			_gr->GetHistogram()->GetXaxis()->SetTitle("#lambda in nm");
			_gr->GetHistogram()->GetYaxis()->SetTitle("Intensity in dB");
			c1->cd(i-NUM_ARGS);
			_gr->Draw("AP");
			_gr->GetYaxis()->SetRangeUser(-80.,-10.);
			_gr->GetXaxis()->SetRangeUser(startwl,stopwl);
			_gr->SetTitle(tmp.c_str());
			c1->Update();
			
			
				//Calculating asymmetry
			std::cout << "maximum: " << max << std::endl;
			double leftlimit, rightlimit = 1;
			leftlimit = findlower(x,y, max);
			rightlimit = findupper(x,y, max);
			if (leftlimit != 1 && rightlimit != 1){
				width_ary[i] = (leftlimit +rightlimit)/2;
			}else{
				width_ary[i] = maxwl;
			}
			double calced_asy = (maxwl-leftlimit)/(rightlimit-maxwl);
			asymmety_ary[i-NUM_ARGS] = calced_asy;
			
			std::cout << "Asymmetry: " << calced_asy << std::endl;
			
		}catch(std::exception e){
			std::cout << e.what()<< std::endl;
		}
	}
	
	
		//Setting style for 3D Plot
	TCanvas *d = new TCanvas("big","big",10,10,1500,800);
	d->Divide(2,2);
	d->cd(1);
	TGraph *the_ints = new TGraph(argc-1,argc_ary,cmp_int);
	the_ints->Draw("A*");
	the_ints->SetTitle("My Ints");
	d->Update();
	d->cd(2);
	std::cout << "Fitting\n\n";
	integral_hist->SetFillColor(kBlue);
		//settig everything to print fitresuts
	gStyle->SetOptStat(1211);
	gStyle->SetOptFit(1111);
	integral_hist->Draw();
	integral_hist->Fit("gaus","W","" ,10,100);
		//integral_hist->Draw("SAME");
	d->Update();
	d->cd(3);
	
	TGraph *roots_int = new TGraph(argc-1, argc_ary, cmp_int_root);
	roots_int->SetTitle("ROOTS Int");
	roots_int->Draw("A*");
	d->Update();
	d->cd(4);
	d->Update();
		//gROOT->SetStyle("modern");
	gr->SetTitle("big");
	gr->GetHistogram("empty")->GetXaxis()->SetTitle("#lambda in nm");
	gr->GetHistogram("empty")->GetXaxis()->SetLimits(startwl,stopwl);
	gr->GetHistogram("empty")->GetYaxis()->SetTitle("Messurement"); 
	gr->GetHistogram("empty")->GetZaxis()->SetTitle("Intensity in dB");
	gr->GetHistogram("empty")->GetXaxis()->SetTitleOffset(1.5);
	gr->GetHistogram("empty")->GetYaxis()->SetTitleOffset(1.5);
	gr->GetHistogram("empty")->GetZaxis()->SetTitleOffset(1.5);
	gr->GetHistogram("empty")->GetZaxis()->SetRangeUser(-70.,max);
	gr->GetHistogram("empty")->GetXaxis()->CenterTitle();
	gr->GetHistogram("empty")->GetYaxis()->CenterTitle();
	gr->GetHistogram("empty")->GetZaxis()->CenterTitle();
	gr->Draw("PCOL");
	d->SetFillColor(16);
	
	
#ifdef RENDER
		//Render 3D animation
	const Int_t kUPDATE = 1;
	TSlider *slider = 0;
	
	for (Int_t i = 1; i <= 125; i++){
		TView3D *v = new TView3D();
		v->RotateView(5+i,45+i,d);
			//d->Update();
		
		if(i && (i%kUPDATE)== 0){
			if (i == kUPDATE){
				gr->Draw("PCOL");
				d->Update();
				slider = new TSlider("slider","test",850,-70,856,max);
			}
			if (slider) slider->SetRange(0,Float_t(i)/10000.);
			d->Modified();
			d->Update();
			d->Print("3d.gif+");
		} 
	}
	d->Update();
	d->Print("3d.gif++");
#endif
	
	
		//Saving image
	TImage *img = TImage::Create();
	boost::filesystem::path p(t->Argv(3));
	std::string file = p.parent_path().string();
	file += "_big.png";
	img->FromPad(d);
	img->WriteImage(file.c_str());
		//cleaning
	
	TCanvas *e = new TCanvas("Asymmetry","Asymmetry",10,10,1500,800);
	e->Divide(2,1);
	TGraph *asy_plot = new TGraph(argc-1, argc_ary, asymmety_ary);
	e->cd(1);
	asy_plot->SetTitle("Asymmetry");
	asy_plot->GetHistogram()->GetXaxis()->SetTitle("# Meassurement");
	asy_plot->GetHistogram()->GetYaxis()->SetTitle("Asymmetry");
	asy_plot->GetHistogram()->GetXaxis()->SetRange(1, argc);
	asy_plot->Draw("A*");
	e->Update();
	e->cd(2);
	
	
	TGraph *center_plot = new TGraph(argc-1 , argc_ary, width_ary);
	center_plot->GetHistogram()->GetXaxis()->SetTitle("# Meassurement");
	center_plot->GetHistogram()->GetYaxis()->SetTitle("Center in nm");
	center_plot->GetHistogram()->GetYaxis()->SetRangeUser(startwl, stopwl);
	center_plot->SetTitle("Center");
	center_plot->Draw("A*");
	e->Update();
		//Saving Images
	TImage *secimg = TImage::Create();
	boost::filesystem::path p2(t->Argv(3));
	file = p2.parent_path().string();
	file += "_asy_cent.png";
	secimg->FromPad(e);
	secimg->WriteImage(file.c_str());
	
	TImage *thrdimg = TImage::Create();
	boost::filesystem::path p3(t->Argv(3));
	file = p3.parent_path().string();
	file += "_allplots.png";
	thrdimg->FromPad(c1);
	thrdimg->WriteImage(file.c_str());
	
		//detecting Gradients
	gradient(asymmety_ary, width_ary,cmp_int, argc-1,c1);
	std::cout << "\n\n\nDone !!\nYou can quit now using CTRL+C \n" ;
	
	if (run == true){
		t->Run();
	}
	std::cout << "With \n" ;
	
	delete[] cmp_int;
	delete[] argc_ary; 
	delete[] cmp_int_root;
	delete[] asymmety_ary;
	delete[] width_ary;
	return 0;
}
int main(int argc, char * argv[]){
	// declaring and initializing some variables. Most of them will be set according to command line options passed to the program after parsing of command line arguments. However, if Boost is not used, the only available command line option is the number of events to generate; other variables will use the values set below
	std::size_t nevents = 0; // number of events to generate
	std::string pythia_cfgfile = "Z2uubar.cmnd"; // name of PYTHIA cofiguration file
	std::string output_filename = "Z2uubar.root"; // name of the output file
	bool verbose = false; // increased verbosity switch

	#ifdef USE_BOOST
		try {
			boost::program_options::options_description desc("Usage");

			// defining command line options. See boost::program_options documentation for more details
			desc.add_options()
							("help", "produce this help message")
							("nevents,n", boost::program_options::value<std::size_t>(&nevents), "number of events to generate")
							("pythiacfg,P", boost::program_options::value<std::string>(&pythia_cfgfile)->default_value("Z2uubar.cmnd"), "PYTHIA config file")
							("outfile,o", boost::program_options::value<std::string>(&output_filename)->default_value("Z2uubar.root"), "Output file")
							("verbose,v", boost::program_options::bool_switch()->default_value(false), "Run with increased verbosity")
			;
			boost::program_options::variables_map vm;
			boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
			boost::program_options::notify(vm);

			if(vm.find("help") != vm.end() || argc < 2) {
				std::cout << "Generator of inclusive events. Version " << Generator_VERSION_MAJOR << '.' << Generator_VERSION_MINOR << std::endl;
				std::cout << desc << std::endl;

				return EXIT_SUCCESS;
			}

			verbose = vm.at("verbose").as<bool>();
		} catch(std::exception const & e) {
			std::cout << e.what() << std::endl;

			return EXIT_FAILURE;
		}
	#else
		if(argc < 2) {
			std::cout << "Generator of inclusive events. Version " << Generator_VERSION_MAJOR << '.' << Generator_VERSION_MINOR << std::endl;
			std::cout << "Usage: " << argv[0] << " n, where \"n\" is a number of events to generate" << std::endl;
			std::cout << "WARNING! This version of the generator does not use program options parser, which means that you are personally responsible for providing correct options to this program." << std::endl;

			return EXIT_SUCCESS;
		} else {
			nevents = std::stoull(argv[1]);
		}
	#endif

	auto start_time = std::chrono::system_clock::now();
	auto last_timestamp = start_time;

	if(verbose) {
			std::cout << "PYTHIA config file: \"" << pythia_cfgfile << "\"" << std::endl << nevents << " events will be generated." << std:: endl;
	}

	if(verbose) {
		std::cout << "Prepairing data store" << std::endl;
	}

	// prepairing event store
	podio::EventStore store;
	podio::ROOTWriter writer(output_filename, &store);

	// registering collections
	auto & evinfocoll = store.create<fcc::EventInfoCollection>("EventInfo");
	auto & pcoll = store.create<fcc::MCParticleCollection>("GenParticle");
	auto & vcoll = store.create<fcc::GenVertexCollection>("GenVertex");

	writer.registerForWrite<fcc::EventInfoCollection>("EventInfo");
	writer.registerForWrite<fcc::MCParticleCollection>("GenParticle");
	writer.registerForWrite<fcc::GenVertexCollection>("GenVertex");

	if(verbose) {
		std::cout << "Initializing PYTHIA" << std::endl;
	}

	// initializing PYTHIA
	Pythia8::Pythia pythia; // creating PYTHIA generator object
	pythia.readFile(pythia_cfgfile); // reading settings from file

	pythia.init(); // initializing PYTHIA generator

	// Interface for conversion from Pythia8::Event to HepMC event.
	HepMC::Pythia8ToHepMC ToHepMC;

	std::size_t counter = 0; // number of "interesting" (that satisfy all the requirements) events generated so far
	std::size_t total = 0; // total number of events generated so far

	if(verbose) {
		std::cout << "Starting to generate events" << std::endl;
	}

	std::map<std::size_t, std::size_t> stable_ptcs_count;

	while(counter < nevents) {
		if(pythia.next()) {
			++total;

			// creating HepMC event storage
			HepMC::GenEvent * hepmcevt = new HepMC::GenEvent(HepMC::Units::GEV, HepMC::Units::MM);

			// converting generated event to HepMC format
			ToHepMC.fill_next_event(pythia, hepmcevt);

			auto nstable = std::count_if(hepmcevt->particles_begin(), hepmcevt->particles_end(), [](HepMC::GenParticle const * const ptc_ptr) {return ptc_ptr->status() == 1;});

			if(nstable <= 7) {
				stable_ptcs_count[nstable]++;
				++counter;

				if(verbose && counter % 100 == 0) {
					std::cout << counter << " events with with 7 or less particles in the final state have been generated (" << total << " total). " << std::chrono::duration<double>(std::chrono::system_clock::now() - last_timestamp).count() / 100 << "events / sec" << std::endl;
					last_timestamp = std::chrono::system_clock::now();
				}

				// filling event info
				auto evinfo = fcc::EventInfo();
				evinfo.Number(counter); // Number takes int as its parameter, so here's a narrowing conversion (std::size_t to int). Should be safe unless we get 2^32 events or more. Then undefined behaviour
				evinfocoll.push_back(evinfo);

				// filling vertices
				std::unordered_map<HepMC::GenVertex *, fcc::GenVertex> vtx_map;
				for(auto iv = hepmcevt->vertices_begin(), endv = hepmcevt->vertices_end(); iv != endv; ++iv) {
					auto vtx = fcc::GenVertex();
					vtx.Position().X = (*iv)->position().x();
					vtx.Position().Y = (*iv)->position().y();
					vtx.Position().Z = (*iv)->position().z();
					vtx.Ctau((*iv)->position().t());
					vtx_map.emplace(*iv, vtx);

					vcoll.push_back(vtx);
				}

				// filling particles
				for(auto ip = hepmcevt->particles_begin(), endp = hepmcevt->particles_end(); ip != endp; ++ip) {
					auto ptc = fcc::MCParticle();
					auto & core = ptc.Core();
					core.Type = (*ip)->pdg_id();
					core.Status = (*ip)->status();

					core.Charge = pythia.particleData.charge(core.Type); // PYTHIA returns charge as a double value (in case it's quark), so here's a narrowing conversion (double to int), but here it's safe
					core.P4.Mass = (*ip)->momentum().m();
					core.P4.Px = (*ip)->momentum().px();
					core.P4.Py = (*ip)->momentum().py();
					core.P4.Pz = (*ip)->momentum().pz();

					auto prodvtx = vtx_map.find((*ip)->production_vertex());
					if(prodvtx != vtx_map.end()) {
						ptc.StartVertex(prodvtx->second);
					}
					auto endvtx = vtx_map.find((*ip)->end_vertex());
					if(endvtx != vtx_map.end()) {
						ptc.EndVertex(endvtx->second);
					}

					pcoll.push_back(ptc);
				}

				writer.writeEvent();
				store.clearCollections();
			}

			// freeing resources
			if(hepmcevt) {
				delete hepmcevt;
				hepmcevt = nullptr;
			}
		}
	}

	writer.finish();

	std::cout << counter << " events with 7 or less particles in the final state have been generated (" << total << " total)." << std::endl;
	for(auto const & nv : stable_ptcs_count) {
		std::cout << std::setw(4) << std::right << nv.first << std::setw(4) << std::right << nv.second << "(" << static_cast<long double>(nv.second) * static_cast<long double>(100) / static_cast<long double>(total) << "%)" << std::endl;
	}
	auto elapsed_seconds = std::chrono::duration<double>(std::chrono::system_clock::now() - start_time).count();
	std::cout << "Elapsed time: " << elapsed_seconds << " s (" << static_cast<long double>(counter) / static_cast<long double>(elapsed_seconds) << " events / s)" << std::endl;

	return EXIT_SUCCESS;
}
Exemple #29
0
int main(int argc, char* argv[]) {
  namespace po = boost::program_options;
  unsigned short port;
  po::options_description desc("Allowed options");
  desc.add_options()("help", "show help message")("version", "show version")
#if defined(HAVE_FORK)
      ("daemon", "daemonize")
#endif
          ("port,p", po::value<unsigned short>(&port)->required(), "port");
  po::variables_map vm;
  try {
    po::store(po::parse_command_line(argc, argv, desc), vm);
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
    return 1;
  }
  if (vm.count("help")) {
    std::cout << desc << std::endl;
    return 0;
  }
  if (vm.count("version")) {
    std::cout << argv[0] << ' ' << PROJECT_VERSION << std::endl;
    return 0;
  }
  try {
    po::notify(vm);
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
    return 1;
  }
  boost::asio::io_service io_service;
#if defined(HAVE_FORK)
  if (vm.count("daemon")) {
    io_service.notify_fork(boost::asio::io_service::fork_prepare);

    pid_t pid = ::fork();
    if (pid > 0) {
      // Parent process, return and keep running
      return 0;
    } else if (pid == -1) {
      // Report error. Might be syslog call aswell.
      std::cerr << "fork #1 failed" << std::endl;
      std::exit(1);
    }

    // Make the process a new session leader. This detaches it from the
    // terminal.
    ::setsid();

    // A process inherits its working directory from its parent. This could be
    // on a mounted filesystem, which means that the running daemon would
    // prevent this filesystem from being unmounted. Changing to the root
    // directory avoids this problem.
    ::chdir("/");

    // The file mode creation mask is also inherited from the parent process.
    // We don't want to restrict the permissions on files created by the
    // daemon, so the mask is cleared.
    ::umask(0);

    // Service forks here
    pid = ::fork();
    if (pid > 0) {
      // Parent process, return and keep running
      std::exit(0);
    } else if (pid == -1) {
      std::cerr << "fork #2 failed" << std::endl;
      std::exit(1);
    }

    // Close the standard streams. This decouples the daemon from the terminal
    // that started it.
    ::close(0);
    ::close(1);
    ::close(2);

    // Inform the io_service that we have finished becoming a daemon. The
    // io_service uses this opportunity to create any internal file descriptors
    // that need to be private to the new process.
    io_service.notify_fork(boost::asio::io_service::fork_parent);
  }
#endif
  try {
    // Prepare server
    boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), port);
    TcpServer server(io_service, endpoint);
    server.start();
    io_service.run();
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
    return 1;
  }
}
int main(int argc, char** argv) {
    boost::timer::auto_cpu_timer t;

    std::string description = std::string("Compute the clique scores for a Markov network from a csv file.  Example usage: ") + argv[0] + " iris.csv iris.css";
    po::options_description desc(description);

    desc.add_options()
            ("input", po::value<std::string > (&inputFile)->required(), "The input file. First positional argument.")
            ("output", po::value<std::string > (&outputFile)->required(), "The output file. Second positional argument.")
            ("delimiter,d", po::value<char> (&delimiter)->required()->default_value(','), "The delimiter of the input file.")
            ("constraints,c", po::value<std::string > (&constraintsFile), "The file specifying constraints on the scores. Constraints are currently unsupported.")
            ("rMin,m", po::value<int> (&rMin)->default_value(5), "The minimum number of records in the AD-tree nodes.")
            ("function,f", po::value<std::string > (&sf)->default_value("BDeu"), "The scoring function to use.")
            ("sfArgument,a", po::value<std::string> (&sfArgument)->default_value("1.0"), "The equivalent sample size, if BDeu is used.")
            ("maxClique,m", po::value<int> (&maxClique)->default_value(0), "The maximum number of variables in any clique (inclusive). A value less than 1 means no limit.")
            ("threads,t", po::value<int> (&threadCount)->default_value(1), "The number of separate threads to use for score calculations.  Multi-threading is currently unsupported.")
            ("time,r", po::value<int> (&runningTime)->default_value(-1), "The maximum amount of time to use. A value less than 1 means no limit.")
            ("hasHeader,s", "Add this flag if the first line of the input file gives the variable names.")
            ("help,h", "Show this help message.")
            ;

    po::positional_options_description positionalOptions;
    positionalOptions.add("input", 1);
    positionalOptions.add("output", 1);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(desc)
            .positional(positionalOptions).run(),
            vm);

    if (vm.count("help") || argc == 1) {
        std::cout << desc;
        return 0;
    }

    po::notify(vm);

    hasHeader = vm.count("hasHeader");

    // no multithreading right now
    threadCount = 1;
    if (threadCount < 1) {
        threadCount = 1;
    }

    printf("URLearning, Markov Network Score Calculator\n");
    printf("Input file: '%s'\n", inputFile.c_str());
    printf("Output file: '%s'\n", outputFile.c_str());
    printf("Delimiter: '%c'\n", delimiter);
    printf("Constraints file: '%s'\n", constraintsFile.c_str());
    printf("r_min: '%d'\n", rMin);
    printf("Scoring function: '%s'\n", sf.c_str());
    printf("Scoring function argument: '%s'\n", sfArgument.c_str());
    printf("Maximum clique size: '%d'\n", maxClique);
    printf("Threads: '%d'\n", threadCount);
    printf("Running time (per variable): '%d'\n", runningTime);
    printf("Has header: '%s'\n", (hasHeader ? "true" : "false"));


    printf("Parsing input file.\n");
    datastructures::RecordFile recordFile(inputFile, delimiter, hasHeader);
    recordFile.read();

    printf("Initializing data specifications.\n");
    network.initialize(recordFile);

    printf("Creating AD-tree.\n");
    scoring::ADTree *adTree = new scoring::ADTree(rMin);
    adTree->initialize(network, recordFile);
    adTree->createTree();

    if (maxClique > network.size() || maxClique < 1) {
        maxClique = network.size();
    }

    scoring::Constraints *constraints = NULL;
    if (constraintsFile.length() > 0) {
        constraints = scoring::parseConstraints(constraintsFile, network);
    }

    scoringFunction = scoring::createMarkovNetworkScoringFunction(sf, sfArgument, network, adTree, constraints);

    std::vector<boost::thread*> threads;
    for (int thread = 0; thread < threadCount; thread++) {
        boost::thread *workerThread = new boost::thread(scoringThread, thread);
        threads.push_back(workerThread);
    }

    for (auto it = threads.begin(); it != threads.end(); it++) {
        (*it)->join();
    }


    // concatenate all of the files together
    std::ofstream out(outputFile, std::ios_base::out | std::ios_base::binary);

    // first, the header information
    std::string header = "META css_version = 0.1\nMETA input_file=" + inputFile + "\nMETA num_records=" + TO_STRING(recordFile.size()) + "\n";
    header += "META clique_limit=" + TO_STRING(maxClique) + "\nMETA score_type=" + sf + "\nMETA score_argument=" + TO_STRING(sfArgument) + "\n\n";
    out.write(header.c_str(), header.size());
    
    // now, write all of the variable information
    for (int variable = 0; variable < network.size(); variable++) {

        datastructures::Variable *var = network.get(variable);
        std::string variableHeader = "VAR " + var->getName() + "\n";
        variableHeader += "META arity=" + TO_STRING(var->getCardinality()) + "\n";
        
        variableHeader += "META values=";
        for (int i = 0; i < var->getCardinality(); i++) {
            variableHeader += var->getValue(i).c_str();
            variableHeader += " ";
        }
        variableHeader += "\n";
        
        out.write(variableHeader.c_str(), variableHeader.size());
    }
    

    for (int thread = 0; thread < threadCount; thread++) {
        std::string threadFilename = outputFile + "." + TO_STRING(thread);
        std::ofstream threadFile(threadFilename, std::ios_base::in | std::ios_base::binary);

        out << threadFile.rdbuf();
        threadFile.close();

        // and remove the variable file
        remove(threadFilename.c_str());
    }

    out.close();
}