예제 #1
0
int main(int argc, char **argv){
int rank, nranks;         // MPI variables.
int nthrds, thrd, cpuid;  //Thread info
int requested=MPI_THREAD_MULTIPLE, provided;

int nsec = 10;     // Load, default time

int ierr;          // Error number

// cmdln_get_nsec_or_help( &nsec, argc, argv); //optional, get nsec from cmd line
   Maskopts opts(argc,argv);

                  // thread safe init replaces MPI_Init(&argc, &argv);
   MPI_Init_thread(&argc, &argv, requested, &provided);  
   MPI_Comm_size(MPI_COMM_WORLD, &nranks);
   MPI_Comm_rank(MPI_COMM_WORLD, &rank);

   mpi_report_mask();   // Report JUST MPI process masks

   #pragma omp parallel private(thrd,nthrds,ierr)
   {
      thrd   =   omp_get_thread_num();
      nthrds =   omp_get_num_threads();

  //  cpuid  =   thrd;                     // set cpuid to thread number (thrd)
  //  ierr   =   map_to_cpuid( cpuid );    // set your own affinity here 

      hybrid_report_mask();        // Call mask reporter

      load_cpu_nsec( nsec );       // Load up rank process so user can watch top.

   }

   MPI_Finalize();

}
예제 #2
0
int main(int argc, char **argv) {
    // Command line options
    std::string address("127.0.0.1:5672/examples");
    options opts(argc, argv);
    opts.add_value(address, 'a', "address", "connect and send to URL", "URL");

    try {
        opts.parse();

        std::vector<std::string> requests;
        requests.push_back("Twas brillig, and the slithy toves");
        requests.push_back("Did gire and gymble in the wabe.");
        requests.push_back("All mimsy were the borogroves,");
        requests.push_back("And the mome raths outgrabe.");
        client handler(address, requests);
        proton::io::socket::engine(address, handler).run();
        return 0;
    } catch (const bad_option& e) {
        std::cout << opts << std::endl << e.what() << std::endl;
    } catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
    return 1;
}
예제 #3
0
boost::program_options::options_description generic_options::all_options() const
{
    boost::program_options::options_description opts("Generic options");
    opts.add_options()
        ("help,h",
            "produce help message")
        ("version,V",
            boost::program_options::value<bool>()
                ->default_value(false)
                ->zero_tokens(),
            "program version")
        ("verbose,v",
            boost::program_options::value<size_t>()
                ->default_value(0)
                ->implicit_value(1)
                ->zero_tokens(),
            "verbose")
        ("logfile,l",
            boost::program_options::value<std::string>()
                ->default_value("/dev/stdout"),
            "logfile")
        ;
    return opts;
}
예제 #4
0
/*
 *   Run pre-initialization 
 */
void vm_run_preinit(CVmFile *origfp, const char *image_fname,
                    CVmFile *newfp, class CVmHostIfc *hostifc,
                    class CVmMainClientIfc *clientifc, 
                    const char *const *argv, int argc,
                    class CVmRuntimeSymbols *runtime_symtab,
                    class CVmRuntimeSymbols *runtime_macros)
{
    vm_globals *vmg__;
    CVmImageLoader *volatile loader = 0;
    CVmImageFile *volatile imagefp = 0;

    /* initialize the VM */
    vm_init_options opts(hostifc, clientifc);
    vm_initialize(&vmg__, &opts);

    /* 
     *   turn off "more" on the console - when running preinitialization,
     *   any output is purely diagnostic information for the programmer
     *   and thus should be formatted as simple stdio-style console output 
     */
    G_console->set_more_state(FALSE);

    err_try
    {
        /* note where the image file starts */
        long start_pos = origfp->get_pos();
        
        /* create the loader */
        imagefp = new CVmImageFileExt(origfp);
        loader = new CVmImageLoader(imagefp, image_fname, 0);

        /* load the image */
        loader->load(vmg0_);

        /* set pre-init mode */
        G_preinit_mode = TRUE;

        /* run it, using the runtime symbols the caller sent us */
        loader->run(vmg_ argv, argc, runtime_symtab, runtime_macros, 0);

        /* 
         *   seek back to the start of the image file, since we need to
         *   copy parts of the original file to the new file 
         */
        origfp->set_pos(start_pos);

        /* save the new image file */
        vm_rewrite_image(vmg_ origfp, newfp, loader->get_static_cs_ofs());
    }
    err_finally
    {
        /* detach the pools from the image file */
        if (loader != 0)
            loader->unload(vmg0_);

        /* delete the loader and the image file object */
        if (loader != 0)
            delete loader;
        if (imagefp != 0)
            delete imagefp;

        /* terminate the VM */
        vm_terminate(vmg__, clientifc);
    }
    err_end;
}
예제 #5
0
/*
 *   Execute an image file.  If an exception occurs, we'll display a
 *   message on the console, and we'll return the error code; we'll return
 *   zero on success.  If an error occurs, we'll fill in 'errbuf' with a
 *   message describing the problem.  
 */
int vm_run_image(CVmMainClientIfc *clientifc,
                 const char *image_file_name,
                 class CVmHostIfc *hostifc,
                 const char *const *prog_argv, int prog_argc,
                 const char *script_file, int script_quiet,
                 const char *log_file, const char *cmd_log_file,
                 int load_from_exe, int show_banner,
                 const char *charset, const char *log_charset,
                 const char *saved_state, const char *res_dir)
{
    CVmFile *fp = 0;
    CVmImageLoader *volatile loader = 0;
    CVmImageFile *volatile imagefp = 0;
    unsigned long image_file_base = 0;
    int retval;
    vm_globals *vmg__;

    /* presume we will return success */
    retval = 0;

    /* create the file object */
    fp = new CVmFile();

    /* initialize the VM */
    vm_init_options opts(hostifc, clientifc, charset, log_charset);
    vm_initialize(&vmg__, &opts);

    /* tell the client system to initialize */
    clientifc->client_init(VMGLOB_ADDR, script_file, script_quiet,
                           log_file, cmd_log_file,
                           show_banner ? T3VM_BANNER_STRING : 0);

    /* catch any errors that occur during loading and running */
    err_try
    {
        /* remember the name of the byte-code file */
        strncpy(G_os_gamename, image_file_name, sizeof(G_os_gamename));
        G_os_gamename[sizeof(G_os_gamename) - 1] = '\0';

        if (load_from_exe)
        {
            osfildef *exe_fp;

            /* find the image within the executable */
            exe_fp = os_exeseek(image_file_name, "TGAM");
            if (exe_fp == 0)
                err_throw(VMERR_NO_IMAGE_IN_EXE);

            /* 
             *   set up to read from the executable at the location of the
             *   embedded image file that we just found 
             */
            image_file_base = osfpos(exe_fp);
            fp->set_file(exe_fp, image_file_base);
        }
        else
        {
            /* reading from a normal file - open the file */
            fp->open_read(image_file_name, OSFTT3IMG);
        }

        /* create the loader */
        imagefp = new CVmImageFileExt(fp);
        loader = new CVmImageLoader(imagefp, image_file_name,
                                    image_file_base);

        /* load the image */
        loader->load(vmg0_);

        /* if we have a resource root path, tell the host interface */
        if (res_dir != 0)
            hostifc->set_res_dir(res_dir);

        /* let the client prepare for execution */
        clientifc->pre_exec(VMGLOB_ADDR);

        /* run the program from the main entrypoint */
        loader->run(vmg_ prog_argv, prog_argc, 0, saved_state);

        /* tell the client we're done with execution */
        clientifc->post_exec(VMGLOB_ADDR);
    }
    err_catch(exc)
    {
        char errbuf[512];

        /* tell the client execution failed due to an error */
        clientifc->post_exec_err(VMGLOB_ADDR);

        /* note the error code for returning to the caller */
        retval = exc->get_error_code();

        /* get the message for the error */
        CVmRun::get_exc_message(vmg_ exc, errbuf, sizeof(errbuf), TRUE);
        
        /* display the message */
        clientifc->display_error(VMGLOB_ADDR, errbuf, FALSE);
    }
    err_end;

    /* unload the image */
    if (loader != 0)
        loader->unload(vmg0_);

    /* delete the loader and the image file object */
    if (loader != 0)
        delete loader;
    if (imagefp != 0)
        delete imagefp;

    /* notify the client */
    clientifc->client_terminate(VMGLOB_ADDR);

    /* terminate the VM */
    vm_terminate(vmg__, clientifc);

    /* delete the file */
    if (fp != 0)
        delete fp;

    /* return the status code */
    return retval;
}
예제 #6
0
int main(int argc, const char** argv)
{
  std::string camera_ip;
  std::uint32_t xmlrpc_port;
  std::string password;
  std::string infile;
  std::string json;

  try
    {
      o3d3xx::CmdLineOpts opts("o3d3xx Config");

      po::options_description config_opts("Config Information");
      config_opts.add_options()
        ("file,f",
         po::value<std::string>()->default_value("-"),
         "Input JSON configuration file");

      opts.visible.add(config_opts);

      if (! opts.Parse(argc, argv, &camera_ip, &xmlrpc_port, &password))
        {
          return 0;
        }

      infile.assign(opts.vm["file"].as<std::string>());

      if (infile == "-")
        {
          std::string line;
          std::ostringstream buff;
          while (std::getline(std::cin, line))
            {
              buff << line << std::endl;
            }

          json.assign(buff.str());
        }
      else
        {
          std::ifstream ifs(infile, std::ios::in);
          if (! ifs)
            {
              throw o3d3xx::error_t(O3D3XX_IO_ERROR);
            }

          json.assign((std::istreambuf_iterator<char>(ifs)),
                      (std::istreambuf_iterator<char>()));
        }

      o3d3xx::Camera::Ptr cam =
        std::make_shared<o3d3xx::Camera>(camera_ip, xmlrpc_port, password);

      cam->FromJSON(json);
    }
  catch (const std::exception& e)
    {
      std::cerr << "Failed to configure camera from JSON config '"
                << infile << "':"
                << std::endl << e.what() << std::endl;
      return 1;
    }

  return 0;
}
예제 #7
0
파일: matmul3d.C 프로젝트: brog2610/quinoa
Main::Main(CkArgMsg* m) {
  if ( (m->argc != 3) && (m->argc != 7) && (m->argc != 10) ) {
    CkPrintf("%s [array_size] [block_size]\n", m->argv[0]);
    CkPrintf("OR %s [array_size_X] [array_size_Y] [array_size_Z] [block_size_X] [block_size_Y] [block_size_Z]\n", m->argv[0]);
    CkPrintf("OR %s [array_size_X] [array_size_Y] [array_size_Z] [block_size_X] [block_size_Y] [block_size_Z] [torus_dim_X] [torus_dim_Y] [torus_dim_Z] \n", m->argv[0]);
    CkAbort("Abort");
  }

  // store the main proxy
  mainProxy = thisProxy;

  // get the size of the global array, size of each chare and size of the torus [optional]
  if(m->argc == 3) {
    arrayDimX = arrayDimY = arrayDimZ = atoi(m->argv[1]);
    blockDimX = blockDimY = blockDimZ = atoi(m->argv[2]);
  }
  else if (m->argc == 7) {
    arrayDimX = atoi(m->argv[1]);
    arrayDimY = atoi(m->argv[2]);
    arrayDimZ = atoi(m->argv[3]);
    blockDimX = atoi(m->argv[4]);
    blockDimY = atoi(m->argv[5]);
    blockDimZ = atoi(m->argv[6]);
  } else {
    arrayDimX = atoi(m->argv[1]);
    arrayDimY = atoi(m->argv[2]);
    arrayDimZ = atoi(m->argv[3]);
    blockDimX = atoi(m->argv[4]);
    blockDimY = atoi(m->argv[5]);
    blockDimZ = atoi(m->argv[6]);
    torusDimX = atoi(m->argv[7]);
    torusDimY = atoi(m->argv[8]);
    torusDimZ = atoi(m->argv[9]);
  }

  if (arrayDimX < blockDimX || arrayDimX % blockDimX != 0)
    CkAbort("array_size_X % block_size_X != 0!");
  if (arrayDimY < blockDimY || arrayDimY % blockDimY != 0)
    CkAbort("array_size_Y % block_size_Y != 0!");
  if (arrayDimZ < blockDimZ || arrayDimZ % blockDimZ != 0)
    CkAbort("array_size_Z % block_size_Z != 0!");

  num_chare_x = arrayDimX / blockDimX;
  num_chare_y = arrayDimY / blockDimY;
  num_chare_z = arrayDimZ / blockDimZ;
  num_chares = num_chare_x * num_chare_y * num_chare_z;

  subBlockDimXz = blockDimX/num_chare_z;
  subBlockDimYx = blockDimY/num_chare_x;
  subBlockDimXy = blockDimX/num_chare_y;

  // print info
  CkPrintf("Running Matrix Multiplication on %d processors with (%d, %d, %d) chares\n", CkNumPes(), num_chare_x, num_chare_y, num_chare_z);
  CkPrintf("Array Dimensions: %d %d %d\n", arrayDimX, arrayDimY, arrayDimZ);
  CkPrintf("Block Dimensions: %d %d %d\n", blockDimX, blockDimY, blockDimZ);

  // Create new array of worker chares
#if USE_TOPOMAP
  CkPrintf("Topology Mapping is being done ...\n");
  CProxy_ComputeMap map = CProxy_ComputeMap::ckNew(num_chare_x, num_chare_y, num_chare_z, 1, 1, 1);
  CkArrayOptions opts(num_chare_x, num_chare_y, num_chare_z);
  opts.setMap(map);
  compute = CProxy_Compute::ckNew(opts);
#elif USE_BLOCKMAP
  CkPrintf("Block Mapping is being done ...\n");
  CProxy_ComputeMap map = CProxy_ComputeMap::ckNew(num_chare_x, num_chare_y, num_chare_z, torusDimX, torusDimY, torusDimZ);
  CkArrayOptions opts(num_chare_x, num_chare_y, num_chare_z);
  opts.setMap(map);
  compute = CProxy_Compute::ckNew(opts);
#else
  compute = CProxy_Compute::ckNew(num_chare_x, num_chare_y, num_chare_z);
#endif

  // CkPrintf("Total Hops: %d\n", hops);

  // Start the computation
  numIterations = 0;
  startTime = CkWallTimer();
#if USE_CKDIRECT
  compute.setupChannels();
#else
  compute.beginCopying();
#endif
}
void GoProject::refreshProjectFile()
{
    RefreshOptions opts(GoProject::ProjectFile | GoProject::Files);
    refresh(opts);
}
예제 #9
0
int
main (int argc, char *argv[])
{
  QCoreApplication::setOrganizationName ("BerndStramm");
  QCoreApplication::setOrganizationDomain ("bernd-stramm.com");
  QCoreApplication::setApplicationName ("navi");
  deliberate::ProgramVersion pv ("Navi");
  QCoreApplication::setApplicationVersion (pv.Version());
  deliberate::DSettings  settings;
  deliberate::SetSettings (settings);
  deliberate::Settings().SetPrefix ("collect_");
  settings.setValue ("program",pv.MyName());


  QStringList  configMessages;

  deliberate::CmdOptions  opts ("navi");
  opts.AddSoloOption ("debug","D",QObject::tr("show Debug log window"));
  opts.AddStringOption ("logdebug","L",QObject::tr("write Debug log to file"));

  deliberate::UseMyOwnMessageHandler ();

  bool optsOk = opts.Parse (argc, argv);
  if (!optsOk) {
    opts.Usage ();
    exit(1);
  }
  if (opts.WantHelp ()) {
    opts.Usage ();
    exit (0);
  }
  configMessages.append (QString("Built on %1 %2")
                         .arg (__DATE__).arg(__TIME__));
  configMessages.append (QObject::tr("Build with Qt %1").arg(QT_VERSION_STR));
  configMessages.append (QObject::tr("Running with Qt %1").arg(qVersion()));

  if (opts.WantVersion ()) {
    exit (0);
  }
  bool showDebug = opts.SeenOpt ("debug");
  int result;
  QApplication  app (argc, argv);

#if DELIBERATE_DEBUG_NOT_NOW
  deliberate::StartDebugLog (showDebug);
  bool logDebug = opts.SeenOpt ("logdebug");
  if (logDebug) {
    QString logfile ("/dev/null");
    opts.SetStringOpt ("logdebug",logfile);
    deliberate::StartFileLog (logfile);
  }
#endif
  
  navi::Collect   collect;

  app.setWindowIcon (collect.windowIcon());
  collect.Init (app);
  collect.AddConfigMessages (configMessages);

  collect.Run (opts.Arguments());
  result = app.exec ();
  qDebug () << " QApplication exec finished " << result;
  return result;
}
예제 #10
0
int main(int argc, const char** argv)
{
  std::string camera_ip;
  std::uint32_t xmlrpc_port;
  std::string password;
  int nframes;
  int nruns;
  bool sw_trigger;
  bool organize;
  double mean = 0.0;

  try
    {
      o3d3xx::CmdLineOpts opts("o3d3xx Frame Grabber Speed");

      po::options_description hz_opts("Hz");
      hz_opts.add_options()
        ("nframes,f",
         po::value<int>()->default_value(10),
         "Number of frames to capture")

        ("nruns,r",
         po::value<int>()->default_value(1),
         "Number of runs to average")

        ("sw,s",
         po::value<bool>()->default_value(false),
         "Software Trigger the FrameGrabber")

        ("organize,o",
         po::value<bool>()->default_value(false),
         "Calls the Organize() hook on the ByteBuffer interface (DEPRECATED)");

      opts.visible.add(hz_opts);

      if (! opts.Parse(argc, argv, &camera_ip, &xmlrpc_port, &password))
        {
          return 0;
        }

      nframes = opts.vm["nframes"].as<int>();
      nruns = opts.vm["nruns"].as<int>();
      sw_trigger = opts.vm["sw"].as<bool>();
      organize = opts.vm["organize"].as<bool>();

      if (nframes <= 0)
        {
          nframes = 10;
        }

      std::vector<double> stats;

      o3d3xx::Camera::Ptr cam =
        std::make_shared<o3d3xx::Camera>(camera_ip, xmlrpc_port, password);

      o3d3xx::FrameGrabber::Ptr fg =
        std::make_shared<o3d3xx::FrameGrabber>(cam);

      o3d3xx::ByteBuffer::Ptr buff =
        std::make_shared<o3d3xx::ByteBuffer>();

      for (int i = 0; i < nruns; i++)
        {
          auto start = std::chrono::steady_clock::now();
          for (int j = 0; j < nframes; j++)
            {
              if (sw_trigger)
                {
                  fg->SWTrigger();
                }

              if (! fg->WaitForFrame(buff.get(), 1000, false, organize))
                {
                  std::cerr << "Timeout waiting for camera!"
                            << std::endl;
                  return -1;
                }
            }
          auto stop = std::chrono::steady_clock::now();
          auto diff = stop - start;
          stats.push_back(std::chrono::duration<double>(diff).count());
        }

      if (nruns >= 1)
        {
          mean =
            std::accumulate<std::vector<double>::iterator,double>(
              stats.begin(), stats.end(), 0.0) / (double) nruns;

          std::cout << "FrameGrabber running at: "
                    << nframes / mean << " Hz"
                    << std::endl
                    << nframes << " frames captured; averaged over "
                    << nruns << " runs"
                    << std::endl;
        }
    }
  catch (const std::exception& e)
    {
      std::cerr << "Failed to compute frame grabber speed: "
                << e.what() << std::endl;
      return 1;
    }

  return 0;
}
예제 #11
0
int main(int argc, const char* argv[])
{
  int idx = -1;
  std::vector<std::uint8_t> bytes;

  std::string camera_ip;
  std::uint32_t xmlrpc_port;
  std::string password;
  std::string outfile;

  try
    {
      o3d3xx::CmdLineOpts opts("o3d3xx IFM Export");

      po::options_description export_opts("Export Information");
      export_opts.add_options()
        ("file,f", po::value<std::string>(), "Output file")
        ("app,a",
         "Flag indicating that the file to export is an application")
        ("config,c",
         "Flag indicating that the file to export is a camera configuration")
        ("index,i", po::value<int>(),
         "Index of the app to export (defaults to current active)");

      opts.visible.add(export_opts);

      if (! opts.Parse(argc, argv, &camera_ip, &xmlrpc_port, &password))
        {
          return 0;
        }

      if (opts.vm.count("app") && opts.vm.count("config"))
        {
          std::cerr << "Only one of `app' or `config' may be supplied!"
                    << std::endl << std::flush;

          throw(o3d3xx::error_t(O3D3XX_INVALID_ARGUMENT));
        }
      else if (! (opts.vm.count("app") || opts.vm.count("config")))
        {
          std::cerr << "Exactly one of `app' or `config' must be supplied!"
                    << std::endl << std::flush;

          throw(o3d3xx::error_t(O3D3XX_INVALID_ARGUMENT));
        }

      outfile.assign(opts.vm["file"].as<std::string>());

      // get the byte buffer from the camera
      o3d3xx::Camera::Ptr cam =
        std::make_shared<o3d3xx::Camera>(camera_ip, xmlrpc_port, password);

      if (opts.vm.count("app"))
        {
          // export an app
          if (opts.vm.count("index"))
            {
              idx = opts.vm["index"].as<int>();
            }

          if (idx == -1)
            {
              idx = cam->GetDeviceConfig()->ActiveApplication();
            }

          bytes = cam->ExportIFMApp(idx);
        }
      else
        {
          // export a configuration
          std::cerr << "Config export: not yet implemented!"
                    << std::endl;
        }

      // write the bytes out to the supplied file
      std::ofstream(outfile, std::ios::binary).
        write((char *)bytes.data(), bytes.size());
    }
  catch (const std::exception& e)
    {
      std::cerr << "Failed to export to file '"
                << outfile << "':"
                << std::endl << e.what() << std::endl;

      return 1;
    }

  return 0;
}
예제 #12
0
파일: main.cpp 프로젝트: TrygveS/sweet.hpp
int main(int argc, char** argv) {
	std::string inputFile;
	std::string outAstH("ast.hpp");
	std::string outAstS("ast.cpp");
	std::string outPrsH("parser.hpp");
	std::string outPrsS("parser.cpp");
	std::string outErrH("error.hpp");
	std::string outErrS("error.cpp");
	std::string outVH("visitor.hpp");
	std::string outVS("visitor.cpp");
	std::string outovH("outvisitor.hpp");
	std::string outovS("outvisitor.cpp");
	std::string outdvH("dotvisitor.hpp");
	std::string outdvS("dotvisitor.cpp");
	std::string outMvH("multivisitor.hpp");
	std::string outMvS("multivisitor.cpp");
	std::string outLamH("lambdavisitor.hpp");
	std::string outLamS("lambdavisitor.cpp");
	std::string outH("visitorinclude");
	std::string outPrefix;
	sweet::Options opts(argc, argv);
	opts.get("-i", "--inputFile", "The grammar file to parse", inputFile);
	opts.get("-ah", "--astoutputheader", "Output file for ast header", outAstH);
	opts.get("-as", "--astoutputsource", "Output file for ast source", outAstS);
	opts.get("-ph", "--parseroutputheader", "Output file for parser header", 
		outPrsH);
	opts.get("-ps", "--parseroutputsource", "Output file for parser source", 
		outPrsS);
	opts.get("-eh", "--erroroutputheader", "Output file for error header", 
		outErrH);
	opts.get("-es", "--erroroutputsource", "Output file for error source", 
		outErrS);
	opts.get("-vh", "--visitoroutputheader", 
		"Output file for tree visitor header", outVH);
	opts.get("-vs", "--visitoroutputsource", 
		"Output file for tree visitor source", outVS);
	opts.get("-oh", "--outvisitoroutputheader", 
		"Output file for std::cout visitor header", outovH);
	opts.get("-os", "--outvisitoroutputsource", 
		"Output file for std::cout visitor source", outovS);
	opts.get("-dh", "--dotvisitoroutputheader", 
		"Output file for Dot file visitor header", outdvH);
	opts.get("-ds", "--dotvisitoroutputsource", 
		"Output file for Dot file visitor source", outdvS);
	opts.get("-mh", "--multivisitoroutputheader", 
		"Output file for Multi visitor header", outMvH);
	opts.get("-ms", "--multivisitoroutputsource", 
		"Output file for Multi visitor source", outMvS);
	opts.get("-lh", "--lambdavisitorheader", 
		"Output file for Lambda visitor header", outLamH);
	opts.get("-ls", "--lambdavisitorsource", 
		"Output file for Lambda visitor source", outLamS);
	opts.get("-op", "--outputprefix", 
		"All output files will be prefixed with this string", outPrefix);
	opts.get("-in", "--visitorinclude", 
		"Visitor method declarations", outH);
	opts.finalize();

	if(!outPrefix.empty()) {
		outAstH = outPrefix + outAstH;
		outAstS = outPrefix + outAstS;
		outPrsH = outPrefix + outPrsH;
		outPrsS = outPrefix + outPrsS;
		outErrH = outPrefix + outErrH;
		outErrS = outPrefix + outErrS;
		outVH = outPrefix + outVH;
		outVS = outPrefix + outVS;
		outovH = outPrefix + outovH;
		outovS = outPrefix + outovS;
		outdvH = outPrefix + outdvH;
		outdvS = outPrefix + outdvS;
		outMvH = outPrefix + outMvH;
		outMvS = outPrefix + outMvS;
		outLamS = outPrefix + outLamS;
		outLamH = outPrefix + outLamH;
		outH = outPrefix + outH;
	}

	if(inputFile.empty()) {
		return 0;
	}

	RuleStore store;
	RuleParser parser(inputFile, store);
	parser.parse();
	std::ofstream astH(outAstH);
	std::ofstream astS(outAstS);
	std::ofstream prsH(outPrsH);
	std::ofstream prsS(outPrsS);
	std::ofstream errH(outErrH);
	std::ofstream errS(outErrS);
	std::ofstream visS(outVS);
	std::ofstream visH(outVH);
	std::ofstream ovisH(outovH);
	std::ofstream ovisS(outovS);
	std::ofstream dvisH(outdvH);
	std::ofstream dvisS(outdvS);
	std::ofstream mvisH(outMvH);
	std::ofstream mvisS(outMvS);
	std::ofstream lamH(outLamH);
	std::ofstream lamS(outLamS);
	std::ofstream inH(outH);
	Output out(prsS,prsH,astS,astH,errS,errH,visS,visH,ovisH,ovisS,dvisH,dvisS,
		mvisH,mvisS,lamS,lamH,inH
	);
	RecurDec rd(store, out);
	rd.computeFirstSet();
	//std::cout<<store.first<<std::endl;

	for(auto& it : store.token) {
		LOG("%s\n", it.second);
	}
	for(auto& it : store.rules) {
		LOG("%s : %s\n", it.first, it.second);
	}
	std::cout<<std::endl;
	sweet::enableLogger(64);
	rd.gen();
	LOG("%s\n%s\n", outPrsH, outPrsS);
	return 0;
}
예제 #13
0
/**
 *  SkDecodingImageGenerator has an Options struct which lets the
 *  client of the generator set sample size, dithering, and bitmap
 *  config.  This test loops through many possible options and tries
 *  them on a set of 5 small encoded images (each in a different
 *  format).  We test both SkData and SkStreamRewindable decoding.
 */
DEF_TEST(ImageDecoderOptions, reporter) {
    const char* files[]  = {
        "randPixels.bmp",
        "randPixels.jpg",
        "randPixels.png",
        "randPixels.webp",
        #if !defined(SK_BUILD_FOR_WIN)
        // TODO(halcanary): Find out why this fails sometimes.
        "randPixels.gif",
        #endif
    };

    SkString resourceDir = GetResourcePath();
    if (!sk_exists(resourceDir.c_str())) {
        return;
    }

    int scaleList[] = {1, 2, 3, 4};
    bool ditherList[] = {true, false};
    SkColorType colorList[] = {
        kAlpha_8_SkColorType,
        kRGB_565_SkColorType,
        kARGB_4444_SkColorType,  // Most decoders will fail on 4444.
        kN32_SkColorType
        // Note that indexed color is left out of the list.  Lazy
        // decoding doesn't do indexed color.
    };
    const bool useDataList[] = {true, false};

    for (size_t fidx = 0; fidx < SK_ARRAY_COUNT(files); ++fidx) {
        SkString path = SkOSPath::SkPathJoin(resourceDir.c_str(), files[fidx]);
        if (!sk_exists(path.c_str())) {
            continue;
        }

        SkAutoDataUnref encodedData(SkData::NewFromFileName(path.c_str()));
        REPORTER_ASSERT(reporter, encodedData.get() != NULL);
        SkAutoTUnref<SkStreamRewindable> encodedStream(
            SkStream::NewFromFile(path.c_str()));
        REPORTER_ASSERT(reporter, encodedStream.get() != NULL);

        for (size_t i = 0; i < SK_ARRAY_COUNT(scaleList); ++i) {
            for (size_t j = 0; j < SK_ARRAY_COUNT(ditherList); ++j) {
                for (size_t m = 0; m < SK_ARRAY_COUNT(useDataList); ++m) {
                    for (size_t k = 0; k < SK_ARRAY_COUNT(colorList); ++k) {
                        SkDecodingImageGenerator::Options opts(scaleList[i],
                                                               ditherList[j],
                                                               colorList[k]);
                        test_options(reporter, opts, encodedStream, encodedData,
                                     useDataList[m], path);

                    }
                    SkDecodingImageGenerator::Options options(scaleList[i],
                                                              ditherList[j]);
                    test_options(reporter, options, encodedStream, encodedData,
                                 useDataList[m], path);
                }
            }
        }
    }
}
bool ParseCommandLine(int argc, char* argv[], std::string& treeFile, std::string& seqCountFile, std::string& outputPrefix, 
											std::string& clusteringMethod, uint& jackknifeRep, uint& seqToDraw, bool& bSampleSize,
											std::string& calcStr, uint& maxDataVecs, bool& bWeighted, bool& bMRCA, bool& bStrictMRCA, bool& bCount, 
											bool& bAll, double& threshold, std::string& outputFile, bool& bVerbose)
{
	bool bShowHelp, bShowCalc, bUnitTests;
	std::string maxDataVecsStr;
	std::string thresholdStr;
	std::string jackknifeRepStr;
	std::string seqToDrawStr;
	GetOpt::GetOpt_pp opts(argc, argv);
	opts >> GetOpt::OptionPresent('h', "help", bShowHelp);
	opts >> GetOpt::OptionPresent('l', "list-calc", bShowCalc);
	opts >> GetOpt::OptionPresent('v', "verbose", bVerbose);
	opts >> GetOpt::OptionPresent('u', "unit-tests", bUnitTests);
	opts >> GetOpt::Option('t', "tree-file", treeFile);
	opts >> GetOpt::Option('s', "seq-count-file", seqCountFile);
	opts >> GetOpt::Option('p', "output-prefix", outputPrefix);
	opts >> GetOpt::Option('g', "clustering", clusteringMethod, "UPGMA");
	opts >> GetOpt::Option('j', "jackknife", jackknifeRepStr, "0");
	opts >> GetOpt::Option('d', "seqs-to-draw", seqToDrawStr, "0");
	opts >> GetOpt::OptionPresent('z', "sample-size", bSampleSize);
	opts >> GetOpt::Option('c', "calculator", calcStr);
	opts >> GetOpt::Option('x', "max-data-vecs", maxDataVecsStr, "1000");
	opts >> GetOpt::OptionPresent('w', "weighted", bWeighted);
	opts >> GetOpt::OptionPresent('m', "mrca", bMRCA);
	opts >> GetOpt::OptionPresent('r', "strict-mrca", bStrictMRCA);
	opts >> GetOpt::OptionPresent('y', "count", bCount);
	opts >> GetOpt::OptionPresent('a', "all", bAll);
	opts >> GetOpt::Option('b', "threshold", thresholdStr, "0.8");
	opts >> GetOpt::Option('o', "output-file", outputFile, "clusters.txt");

	maxDataVecs = atoi(maxDataVecsStr.c_str());
	threshold = atof(thresholdStr.c_str());
	jackknifeRep = atoi(jackknifeRepStr.c_str());
	seqToDraw = atoi(seqToDrawStr.c_str());

	if(bShowHelp || argc <= 1) 
	{		
		std::cout << std::endl;
		std::cout << "Express Beta Diversity (EBD) v1.0.4 (May 24, 2013)" << std::endl;
		std::cout << "  by Donovan Parks ([email protected]) and Rob Beiko ([email protected])" << std::endl;
		std::cout << std::endl;
		std::cout << " Usage: " << opts.app_name() << " -t <tree file> -s <seq file> -c <calculator>" << std::endl;
		std::cout << "  -h, --help           Produce help message." << std::endl;
		std::cout << "  -l, --list-calc      List all supported calculators." << std::endl;
		std::cout << "  -u, --unit-tests     Execute unit tests." << std::endl;
		std::cout << std::endl;
		std::cout << "  -t, --tree-file      Tree in Newick format (if phylogenetic beta-diversity is desired)." << std::endl;
		std::cout << "  -s, --seq-count-file Sequence count file." << std::endl;
		std::cout << "  -p, --output-prefix  Output prefix." << std::endl;
		std::cout << std::endl;
		std::cout << "  -g, --clustering     Hierarchical clustering method: UPGMA, SingleLinkage, CompleteLinkage, NJ (default = UPGMA)." << std::endl;
		std::cout << std::endl;
		std::cout << "  -j, --jackknife      Number of jackknife replicates to perform (default = 0)." << std::endl;
		std::cout << "  -d, --seqs-to-draw   Number of sequence to draw for jackknife replicates." << std::endl;
		std::cout << "  -z, --sample-size    Print number of sequences in each sample." << std::endl;
		std::cout << std::endl;
		std::cout << "  -c, --calculator     Desired calculator (e.g., Bray-Curtis, Canberra)." << std::endl;
		std::cout << "  -w, --weighted       Indicates if sequence abundance data should be used." << std::endl;
		std::cout << "  -m, --mrca           Apply 'MRCA weightings' to each branch (experimental)." << std::endl;
		std::cout << "  -r, --strict-mrca    Restrict calculator to MRCA subtree." << std::endl;
		std::cout << "  -y, --count          Use count data as opposed to relative proportions." << std::endl;
		std::cout << std::endl;
		std::cout << "  -x, --max-data-vecs  Maximum number of profiles (data vectors) to have in memory at once (default = 1000)." << std::endl;
		std::cout << std::endl;
		std::cout << "  -a, --all            Apply all calculators and cluster calculators at the specified threshold." << std::endl;
		std::cout << "  -b, --threshold      Correlation threshold for clustering calculators (default = 0.8)." << std::endl;
		std::cout << "  -o, --output-file    Output file for cluster of calculators (default = clusters.txt)." << std::endl;
		std::cout << std::endl;
		std::cout << "  -v, --verbose        Provide additional information on program execution." << std::endl;
							
    return false;
  }
	else if(bShowCalc)
	{
		std::cout << std::endl;
		std::cout << "Supported calculators: " << std::endl;
		std::cout << "  Bray-Curtis (aka: Sorensen, Steinhaus, Odum, percentage difference, pairwise Whittaker)" << std::endl;
		std::cout << "  Canberra" << std::endl;
		std::cout << "  Chi-squared" << std::endl;
		std::cout << "  Coefficient of similarity (CS)" << std::endl;
		std::cout << "  Complete tree (CT)" << std::endl;
		std::cout << "  Euclidean" << std::endl;
		std::cout << "  Fst (aka: Pst)" << std::endl;
		std::cout << "  Gower" << std::endl;
		std::cout << "  Hellinger" << std::endl;
		std::cout << "  Kulczynski (aka: Kulczynski-Cody, Sokal-Sneath)" << std::endl;
		std::cout << "  Lennon compositional difference (Lennon)" << std::endl;		
		std::cout << "  Manhattan (aka: taxicab, city-block, unnormalized weighted UniFrac)" << std::endl;
		std::cout << "  Mean nearest neighbour distance (MNND)" << std::endl;
		std::cout << "  Mean phylogenetic distance (MPD)" << std::endl;
		std::cout << "  Morisita-Horn" << std::endl;
		std::cout << "  Normalized weighted UniFrac (NWU) (Identical to, but slower, than the Bray-Curtis calculator)" << std::endl;
		std::cout << "  Pearson (i.e., Pearson product-moment correlation coefficient)" << std::endl;		
		std::cout << "  Rao's Hp (RaoHp)" << std::endl;
		std::cout << "  Soergel (aka: Jaccard, unweighted UniFrac, Ruzicka, Marczewski-Steinhaus, percentage remoteness)" << std::endl;
		std::cout << "  Tamas coefficient (TC) (aka: simple matching coefficent)" << std::endl;
		std::cout << "  Weighted correlation (WC)" << std::endl;
		std::cout << "  Whittaker (aka: Whittaker index of association)" << std::endl;	
		std::cout << "  Yue-Clayton (aka: similarity ratio)" << std::endl;
		std::cout << std::endl;

		return false;
	}

	if(bUnitTests)
	{
		std::cout << std::endl;

		UnitTests unitTests;
		if(unitTests.Execute())
			std::cout << "Passed all unit tests." << std::endl;
		else
			std::cerr << "Failed unit test." << std::endl;

		return false;
	}

	if(seqCountFile.empty())
	{
		std::cout << std::endl;
		std::cout << "  [Error] The --seq-count-file (-s) flag must be specified." << std::endl;
		return false;
	}

	if(!bSampleSize && treeFile.empty())
	{
		std::cout << std::endl;
		std::cout << "  [Error] The --tree-file (-t) flag must be specified." << std::endl;
		return false;
	}

	if(jackknifeRep != 0 && seqToDraw == 0)
	{
		std::cout << std::endl;
		std::cout << "  [Error] The --seqs-to-draw (-d) flag must be set along with the --jackknife (-j) flag." << std::endl;
		return false;
	}

	if(bMRCA && bStrictMRCA)
	{
		std::cout << std::endl;
		std::cout << "  [Error] The --mrca (-m) and --strict-mrca (-r) flags cannot be specified at the same time." << std::endl;
		return false;
	}

	if((bMRCA || bStrictMRCA) && treeFile.empty())
	{
		std::cout << std::endl;
		std::cout << "  [Error] A tree file must be specified when using the --mrca (-m) or --strict-mrca (-r) flag." << std::endl;
		return false;
	}

	if(bStrictMRCA && (calcStr == "Normalized weighted UniFrac" || calcStr == "NWU" || calcStr == "NormalizedWeightedUniFrac" || calcStr == "Normalized Weighted UniFrac"))
	{
		std::cout << std::endl;
		std::cout << "  [Error] The --strict-mrca (-r) flag cannot be used with the normalized weighted UniFrac calculator." << std::endl;
		std::cout << "  [Error] Use the Bray-Curtis calculator. It is equivalent to normalized weighted UniFrac." << std::endl;
		return false;
	}

	if(bMRCA && (calcStr == "Normalized weighted UniFrac" || calcStr == "NWU" || calcStr == "NormalizedWeightedUniFrac" || calcStr == "Normalized Weighted UniFrac"))
	{
		std::cout << std::endl;
		std::cout << "  [Error] The --mrca (-m) flag cannot be used with the normalized weighted UniFrac calculator." << std::endl;
		std::cout << "  [Error] Use the Bray-Curtis calculator. It is equivalent to normalized weighted UniFrac." << std::endl;
		return false;
	}

	if(calcStr == "Normalized weighted UniFrac" || calcStr == "NWU" || calcStr == "NormalizedWeightedUniFrac" || calcStr == "Normalized Weighted UniFrac")
	{
		std::cout << "  [Warning] The Normalized weighted UniFrac calculator is equivalent to the Bray-Curtis calculator, but more computationally expensive." << std::endl;
	}

	if(maxDataVecs % 2 != 0)
	{
		std::cout << std::endl;
		std::cout << "  [Error] The --max-data-vecs (-v) parameter must be a multiple of 2." << std::endl;
		return false;
	}

	return true;
}
예제 #15
0
파일: CMT.cpp 프로젝트: yzliang/vcmi
int main(int argc, char** argv)
#endif
{
#ifdef __APPLE__
	// Correct working dir executable folder (not bundle folder) so we can use executable relative pathes
    std::string executablePath = argv[0];
    std::string workDir = executablePath.substr(0, executablePath.rfind('/'));
    chdir(workDir.c_str());
    
    // Check for updates
    OSX_checkForUpdates();

    // Check that game data is prepared. Otherwise run vcmibuilder helper application
    FILE* check = fopen((VCMIDirs::get().localPath() + "/game_data_prepared").c_str(), "r");
    if (check == nullptr) {
        system("open ./vcmibuilder.app");
        return 0;
    }
    fclose(check);
#endif
    std::cout << "Starting... " << std::endl;
	po::options_description opts("Allowed options");
	opts.add_options()
		("help,h", "display help and exit")
		("version,v", "display version information and exit")
		("battle,b", po::value<std::string>(), "runs game in duel mode (battle-only")
		("start", po::value<std::string>(), "starts game from saved StartInfo file")
		("onlyAI", "runs without human player, all players will be default AI")
		("noGUI", "runs without GUI, implies --onlyAI")
		("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
		("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
		("autoSkip", "automatically skip turns in GUI")
		("disable-video", "disable video player")
		("nointro,i", "skips intro movies");

	if(argc > 1)
	{
		try
		{
			po::store(po::parse_command_line(argc, argv, opts), vm);
		}
		catch(std::exception &e) 
		{
            std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
		}
	}

	po::notify(vm);
	if(vm.count("help"))
	{
		prog_help(opts);
		return 0;
	}
	if(vm.count("version"))
	{
		prog_version();
		return 0;
	}
	if(vm.count("noGUI"))
	{
		gNoGUI = true;
		vm.insert(std::pair<std::string, po::variable_value>("onlyAI", po::variable_value()));
	}

	//Set environment vars to make window centered. Sometimes work, sometimes not. :/
	putenv((char*)"SDL_VIDEO_WINDOW_POS");
	putenv((char*)"SDL_VIDEO_CENTERED=1");

	// Have effect on X11 system only (Linux).
	// For whatever reason in fullscreen mode SDL takes "raw" mouse input from DGA X11 extension
	// (DGA = Direct graphics access). Because this is raw input (before any speed\acceleration proceesing)
	// it may result in very small \ very fast mouse when game in fullscreen mode
	putenv((char*)"SDL_VIDEO_X11_DGAMOUSE=0");

    // Init old logging system and new (temporary) logging system
	CStopWatch total, pomtime;
	std::cout.flags(std::ios::unitbuf);
	console = new CConsoleHandler;
	*console->cb = boost::bind(&processCommand, _1);
	console->start();
	atexit(dispose);

	CBasicLogConfigurator logConfig(VCMIDirs::get().userCachePath() + "/VCMI_Client_log.txt", console);
    logConfig.configureDefault();
	logGlobal->infoStream() <<"Creating console "<<pomtime.getDiff();

    // Init filesystem and settings
	preinitDLL(::console);
    settings.init();

    // Initialize logging based on settings
    logConfig.configure();

	// Some basic data validation to produce better error messages in cases of incorrect install
	auto testFile = [](std::string filename, std::string message) -> bool
	{
		if (CResourceHandler::get()->existsResource(ResourceID(filename)))
			return true;

        logGlobal->errorStream() << "Error: " << message << " was not found!";
		return false;
	};

	if (!testFile("DATA/HELP.TXT", "Heroes III data") &&
	    !testFile("MODS/VCMI/MOD.JSON", "VCMI mod") &&
	    !testFile("DATA/StackQueueBgBig.PCX", "VCMI data"))
		exit(1); // These are unrecoverable errors

	// these two are optional + some installs have them on CD and not in data directory
	testFile("VIDEO/GOOD1A.SMK", "campaign movies");
	testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds

	conf.init();
    logGlobal->infoStream() <<"Loading settings: "<<pomtime.getDiff();
    logGlobal->infoStream() << NAME;

	srand ( time(nullptr) );
	

	const JsonNode& video = settings["video"];
	const JsonNode& res = video["screenRes"];

	//something is really wrong...
	if (res["width"].Float() < 100 || res["height"].Float() < 100)
	{
        logGlobal->errorStream() << "Fatal error: failed to load settings!";
        logGlobal->errorStream() << "Possible reasons:";
        logGlobal->errorStream() << "\tCorrupted local configuration file at " << VCMIDirs::get().userConfigPath() << "/settings.json";
        logGlobal->errorStream() << "\tMissing or corrupted global configuration file at " << VCMIDirs::get().userConfigPath() << "/schemas/settings.json";
        logGlobal->errorStream() << "VCMI will now exit...";
		exit(EXIT_FAILURE);
	}

	if(!gNoGUI)
	{
		if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO))
		{
			logGlobal->errorStream()<<"Something was wrong: "<< SDL_GetError();
			exit(-1);
		}
		atexit(SDL_Quit);
		setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
		logGlobal->infoStream() <<"\tInitializing screen: "<<pomtime.getDiff();
	}


	CCS = new CClientState;
	CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler etc.)
	// Initialize video
#if DISABLE_VIDEO
	CCS->videoh = new CEmptyVideoPlayer;
#else
	if (!gNoGUI && !vm.count("disable-video"))
		CCS->videoh = new CVideoPlayer;
	else
		CCS->videoh = new CEmptyVideoPlayer;
#endif

    logGlobal->infoStream()<<"\tInitializing video: "<<pomtime.getDiff();



	//we can properly play intro only in the main thread, so we have to move loading to the separate thread
	boost::thread loading(init);

	if(!gNoGUI )
	{
		if(!vm.count("battle") && !vm.count("nointro"))
			playIntro();
		SDL_FillRect(screen,nullptr,0);
	}

	CSDL_Ext::update(screen);
	loading.join();
    logGlobal->infoStream()<<"Initialization of VCMI (together): "<<total.getDiff();

	if(!vm.count("battle"))
	{
		Settings session = settings.write["session"];
		session["autoSkip"].Bool()  = vm.count("autoSkip");
		session["oneGoodAI"].Bool() = vm.count("oneGoodAI");

		std::string fileToStartFrom; //none by default
		if(vm.count("start"))
			fileToStartFrom = vm["start"].as<std::string>();

		if(fileToStartFrom.size() && boost::filesystem::exists(fileToStartFrom))
			startGameFromFile(fileToStartFrom); //ommit pregame and start the game using settings from fiel
		else
		{
			if(fileToStartFrom.size())
			{
                logGlobal->warnStream() << "Warning: cannot find given file to start from (" << fileToStartFrom
                    << "). Falling back to main menu.";
			}
			GH.curInt = CGPreGame::create(); //will set CGP pointer to itself
		}
	}
	else
	{
		auto  si = new StartInfo();
		si->mode = StartInfo::DUEL;
		si->mapname = vm["battle"].as<std::string>();
		si->playerInfos[PlayerColor(0)].color = PlayerColor(0);
		si->playerInfos[PlayerColor(1)].color = PlayerColor(1);
		startGame(si);
	}

	if(!gNoGUI)
	{
		mainGUIThread = new boost::thread(&CGuiHandler::run, &GH);
		listenForEvents();
	}
	else
	{
		while(true)
			boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
	}

	return 0;
}
예제 #16
0
int 
main(int argc, char **argv) 
{
    // Command line options
    std::string address("127.0.0.1:5672/examples");
    std::string destination(".");
    int message_count = 100;
    int report_frequency = 100000;
    int addr_number  = 0;
    options opts(argc, argv);
    opts.add_value(address, 'a', "address", "connect to and receive from URL", "URL");
    opts.add_value(message_count, 'm', "messages", "receive COUNT messages", "COUNT");
    opts.add_value(addr_number, 'q', "addr", "number of address to recv from", "ADDR");
    opts.add_value(destination, 'd', "dest", "destination dir for reports", "DEST");
    opts.add_value(report_frequency, 'f', "freq", "report frequency", "FREQ");

    try 
    {
      opts.parse();
      std::stringstream output_file_name;
      output_file_name << destination << "/tp_report_" << getpid() << ".txt";

      FILE * output_fp = fopen ( output_file_name.str().c_str(), "w" );
      if ( ! output_fp )
      {
        fprintf ( stderr, "simple_recv can't open output file |%s|\n", destination.c_str());
        exit ( 1 );
      }

      std::stringstream addr;
      addr << address << '/' << addr_number;

      fprintf ( stderr, "recv: receiving from |%s|\n", addr.str().c_str() );

      simple_recv recv ( addr.str(), message_count, output_fp, report_frequency );
      proton::container(recv).run();

      if ( recv.received < recv.expected )
      {
        fprintf ( output_fp, "MDEBUG exiting with failure %.3lf\n", get_timestamp());
        fclose ( output_fp );
        fprintf ( stderr, 
                  "receiver %d exiting with failure. %d of %d messages received.\n", 
                  getpid(),
                  recv.received,
                  recv.expected
                );
        return 1;
      }
      else
      {
        fprintf ( output_fp, "MDEBUG exiting with success %.3lf\n", get_timestamp());
        fclose ( output_fp );
        //fprintf ( stderr, "receiver %d exiting with success.\n", getpid() );
        return 0;
      }
    } 
    catch (const bad_option& e) 
    {
      std::cerr << opts << std::endl << e.what() << std::endl;
    } 
    catch (const std::exception& e) 
    {
      std::cerr << e.what() << std::endl;
    }

    fprintf ( stderr, "receiver exiting with error.\n" );
    return 2;
}
예제 #17
0
파일: staar.cpp 프로젝트: bbitmaster/STAAR
int main(int argc, char* argv[]){
  printHeader();
  int return_value;
  double start = getTime();

  // Parse and error check the command line arguments
  Options opts(argc, argv);

  // Looks like something is wrong with the cmd line args
  // or the user input the -h flag
  if(opts.fail())
    {
      return 1;
    }

  // Lets check to see what kind of input we received for the
  // PDB file.  If we have a list file of PDBs, just go through
  // list with the specified directory. If a directory, parse 
  // all files in the directory. Otherwise just parse the single 
  // file
  if( opts.pdblist )
    {
      return_value = processPDBList(opts);
    }
  else if( opts.chain_list )
    {
      return_value = processPDBChainList(opts);
    }
  else if( isDirectory(opts.pdbfile) )
    {
      // go through each file in the directory
      return_value = processPDBDirectory(opts);
    }
  else
    {
      ofstream output_file(opts.outputfile);
      if(!output_file)
        {
          cerr << red << "Error" << reset << ": Failed to open output file," << opts.outputfile << endl;
          return 1;
        }
      write_output_head(output_file,opts.triplets);
      //open the pair list file (if we're searching for triplets, and if the option to log pairs is specified
      ofstream pairlistfile;

      if(opts.triplets && opts.pairlistfile != NULL){
        pairlistfile.open(opts.pairlistfile);
        if( !pairlistfile)
          {
            cerr << red << "Error" << reset << ": Failed to open pairfile output file" << endl;
            perror("\t");
          }
      }

      return_value = processSinglePDBFile(opts.pdbfile, opts, output_file,pairlistfile);
      if(opts.triplets && opts.pairlistfile != NULL){
        pairlistfile.close();
      }
      output_file.close();
    }

  cout << "Time taken: " << getTime() - start << "s" << endl;
  return !return_value;
}
예제 #18
0
void ChatConnection::Connect()
{
    QStatus status = ER_OK;
    assert(invariants());
    createMessageBus();
    NotifyUser(MSG_STATUS, "Start the message bus.");
    /* Start the msg bus */
    if (ER_OK == status) {
        status = this->busAttachment->Start();
        if (ER_OK != status) {
            NotifyUser(MSG_ERROR, "BusAttachment::Start failed (%s)\n", QCC_StatusText(status));
        }
    }
    /* Register a bus listener */
    if (ER_OK == status) {
        // make sure the callback has been set
        this->busAttachment->RegisterBusListener(*(this->busListener));
    }
    NotifyUser(MSG_STATUS, "Registered BusListener");

    /* Connect to the local daemon */
    NotifyUser(MSG_STATUS, "Connect to the local daemon.");
    if (ER_OK == status) {
        status = this->busAttachment->Connect();
    }
    if (ER_OK != status) {
        NotifyUser(MSG_ERROR, "BusAttachment::Connect(%s) failed (%s)\n", this->busAttachment->GetConnectSpec().c_str(), QCC_StatusText(status));
    }
    if (!this->advertisedName.empty()) {
        NotifyUser(MSG_STATUS, "Request name");
        status = this->busAttachment->RequestName(this->advertisedName.c_str(), DBUS_NAME_FLAG_DO_NOT_QUEUE);
        if (ER_OK != status) {
            NotifyUser(MSG_ERROR, "RequestName(%s) failed (status=%s)\n", this->advertisedName.c_str(), QCC_StatusText(status));
            status = (status == ER_OK) ? ER_FAIL : status;
        }
        /* Bind the session port*/
        NotifyUser(MSG_STATUS, "Bind session port.");
        SessionOpts opts(SessionOpts::TRAFFIC_MESSAGES, true, SessionOpts::PROXIMITY_ANY, TRANSPORT_ANY);
        if (ER_OK == status) {
            SessionPort sp = CHAT_PORT;
            status = this->busAttachment->BindSessionPort(sp, opts, *(this->busListener));
            if (ER_OK != status) {
                NotifyUser(MSG_ERROR, "BindSessionPort failed (%s)\n", QCC_StatusText(status));
            }
        }

        /* Advertise same well-known name */
        if (ER_OK == status) {
            status = this->busAttachment->AdvertiseName(this->advertisedName.c_str(), opts.transports);
            if (status != ER_OK) {
                NotifyUser(MSG_ERROR, "Failed to advertise name %s (%s)\n", this->advertisedName.c_str(), QCC_StatusText(status));
            }
        }
    } else {
        /* Discover name */
        status = this->busAttachment->FindAdvertisedName(this->joinName.c_str());
        if (status != ER_OK) {
            NotifyUser(MSG_ERROR, "org.alljoyn.Bus.FindAdvertisedName failed (%s)\n", QCC_StatusText(status));
        }
        NotifyUser(MSG_STATUS, "Found Advertised Name \n");
    }
    NotifyUser(MSG_STATUS, "Ready...");
}
예제 #19
0
파일: pgm.C 프로젝트: brog2610/quinoa
main::main(CkArgMsg *m)
{ 
  CkGetChareID(&mainhandle);

  int numObjs=-1, numMsgs=-1, msgSize=-1, locality=-1, grainSize=-1;
  int density=-1, i, totalObjs=-1;
  double granularity=-1.0;
  char grainString[20];
  char *text;

  if(m->argc<6) {
    CkPrintf("Usage: simb <#objsPerProc> <#msgsPerObj> <msgSize(MIXED,SMALL,MEDIUM,LARGE)> [-g[f|m|c|z] | -t<granularity> ] <density(msgsPerVTU)>\n");
    CkExit();
  }
  numObjs = atoi(m->argv[1]);
  totalObjs = numObjs * CkNumPes();
  map = (int *)malloc(totalObjs*sizeof(int));
  numMsgs = atoi(m->argv[2]);
  if (strcmp(m->argv[3], "MIXED") == 0)
    msgSize = MIX_MS;
  else if (strcmp(m->argv[3], "SMALL") == 0)
    msgSize = SMALL;
  else if (strcmp(m->argv[3], "MEDIUM") == 0)
    msgSize = MEDIUM;
  else if (strcmp(m->argv[3], "LARGE") == 0)
    msgSize = LARGE;
  else {
    CkPrintf("Invalid message size: %s\n", m->argv[8]);
    CkExit();
  }

  CkPrintf(">>> simb run with %d objects per processor each to send %d messages of %s size...\n", numObjs, numMsgs, m->argv[3]);

  strcpy(grainString, m->argv[4]);
  text = "";
  if (strcmp(grainString, "-gf") == 0) {
    grainSize = FINE; text = "FINE"; }
  else if (strcmp(grainString, "-gm") == 0) {
    grainSize = MEDIUM_GS; text = "MEDIUM"; }
  else if (strcmp(grainString, "-gc") == 0) {
    grainSize = COARSE; text = "COARSE"; }
  else if (strcmp(grainString, "-gz") == 0) {
    grainSize = MIX_GS; text = "MIXED"; }
  else if (strncmp(grainString, "-t", 2) == 0)
    granularity = atof(&(grainString[2]));
  density = atoi(m->argv[5]);

  CkPrintf(">>> ...Each event has %s granularity of %f on average...\n>>> ...Events are concentrated at approximately %d per Virtual Time Unit(VTU).\n", text, granularity, density);

  POSE_init();

  WorkerData *wd;
  wd = new WorkerData;
  wd->numObjs = numObjs;
  wd->numMsgs = numMsgs;
  wd->msgSize = msgSize;
  wd->grainSize = grainSize;
  wd->granularity = granularity;
  wd->density = density;
  wd->Timestamp(0);
  //Create the map group
  CProxy_BlockMap myMap=CProxy_BlockMap::ckNew();
  //Make a new array using that map
  CkArrayOptions opts(totalObjs);
  opts.setMap(myMap);
  POSE_Objects.doneInserting();
  (*(CProxy_worker *) &POSE_Objects) = CProxy_worker::ckNew(wd, opts);
  /*
  // create all the workers
  WorkerData *wd;
  int dest, j;
  srand48(42);
  buildMap(totalObjs, UNIFORM);
  for (i=0; i<totalObjs; i++) {
    wd = new WorkerData;
    wd->numObjs = numObjs;
    wd->numMsgs = numMsgs;
    wd->msgSize = msgSize;
    wd->grainSize = grainSize;
    wd->granularity = granularity;
    wd->density = density;

    dest = map[i];
    wd->Timestamp(0);
    //wd->dump();
    (*(CProxy_worker *) &POSE_Objects)[i].insert(wd, dest);
  }

  SmallWorkMsg *sm = new SmallWorkMsg;
  memset(sm->data, 0, SM_MSG_SZ*sizeof(int));
  sm->fromPE = -1;
  sm->Timestamp(0);
  (*(CProxy_worker *) &POSE_Objects).workSmall(sm);
  */
  POSE_startTimer();
}
예제 #20
0
파일: main.cpp 프로젝트: berndhs/egalite
int
main (int argc, char* argv[])
{
  QCoreApplication::setApplicationName ("egalite");
  QCoreApplication::setOrganizationName ("BerndStramm");
  QCoreApplication::setOrganizationDomain ("bernd-stramm.com");
  deliberate::ProgramVersion pv ("Egalite");
  QCoreApplication::setApplicationVersion (pv.Version());

#if EGALITE_GENCERT
  QCA::Initializer  qcaInit;
#endif
  
  QApplication  app (argc,argv);

  QSettings  settings;
  deliberate::SetSettings (settings);
  settings.setValue ("program",pv.MyName());


  QStringList  configMessages;  
  configMessages.append (QObject::tr("Build with Qt %1").arg(QT_VERSION_STR));
  configMessages.append (QObject::tr("Running with Qt %1").arg(qVersion()));
  
  bool qcaGenerateSupported (false);
  
#if EGALITE_GENCERT
  QCA::scanForPlugins ();
  qcaGenerateSupported = QCA::isSupported ("cert");
#endif
  
  // We need to ensure that we have certificate handling support
  if ( qcaGenerateSupported ) {
    configMessages << "No PKI certificate support on this system" ;
  } else {
    configMessages << " Certificate support available ";
  }
  #if DO_AUDIO
    #if DELIBERATE_QT_AUDIO_OK
    configMessages << QString(" Audio enabled with Qt %1") 
                      .arg (DELIBERATE_QT_NUM) ;
    #else
    configMessages << QString(" No Audio Input with Qt %1") 
                       .arg (DELIBERATE_QT_NUM) ;
    #endif
  #else
    #if DO_MOBI_AUDIO
      #if DELIBERATE_QT_AUDIO_OK
      configMessages << QString(" MobilAudio enabled with Qt %1") 
                        .arg (DELIBERATE_QT_NUM) ;
      #else
      configMessages << QString(" No MobilAudio Input with Qt %1") 
                         .arg (DELIBERATE_QT_NUM) ;
      #endif
    #else
    configMessages << QString (" Audio Disabled in Build Configuration");
    #endif
  #endif
  QString locale = QLocale::system().name();
  QTranslator  translate;
  QString xlateFile (QString ("egalite_") + locale);
  QString langDir (":/translate");
  translate.load (xlateFile, langDir);
  QTextCodec::setCodecForTr (QTextCodec::codecForName ("utf8"));
  app.installTranslator (&translate);

  deliberate::CmdOptions  opts ("Egalite");
  opts.AddSoloOption ("debug","D",QObject::tr("show Debug log window"));
  opts.AddStringOption ("logdebug","L",QObject::tr("write Debug log to file"));
  opts.AddStringOption ("lang","l",
                   QObject::tr("language (2-letter lower case)"));
  opts.AddSoloOption ("phone","P",QObject::tr("use phone user interface"));

 // deliberate::UseMyOwnMessageHandler ();

  bool optsOk = opts.Parse (argc, argv);
  if (!optsOk) {
    opts.Usage ();
    exit(1);
  }
  if (opts.WantHelp ()) {
    opts.Usage ();
    exit (0);
  }
  pv.CLIVersion ();
  for (int cm=0; cm<configMessages.size(); cm++) {
    deliberate::StdOut () << configMessages[cm] << endl;
  }
  if (opts.WantVersion ()) {
    exit (0);
  }
  bool showDebug = opts.SeenOpt ("debug");

  deliberate::StartDebugLog (showDebug);
  bool logDebug = opts.SeenOpt ("logdebug");
  if (logDebug) {
    QString logfile ("/dev/null");
    opts.SetStringOpt ("logdebug",logfile);
    deliberate::StartFileLog (logfile);
  }
  QXmppLogger * xlogger = QXmppLogger::getLogger();
  if (showDebug || logDebug) {
    xlogger->setLoggingType (QXmppLogger::FileLogging);
  } else {
    xlogger->setLoggingType (QXmppLogger::NoLogging);
  }

  if (opts.SeenOpt ("lang")) {
    QString newlocale (locale);
    opts.SetStringOpt ("lang",newlocale);
    if (newlocale != locale) {   
      QString xlateFile (QString ("egalite_") + newlocale);
      QString langDir (":/translate");
      translate.load (xlateFile, langDir);
      QTextCodec::setCodecForTr (QTextCodec::codecForName ("utf8"));
      app.installTranslator (&translate);
    }
  }
  /** the real main program starts here */
  qDebug () << " plugin library paths " <<  QCoreApplication::libraryPaths();

  egalite::DChatMain  chatmain;
#if 0
  QString defaultFamily = QFont().family ();
  QString fontFamily ("default");
  int pointSize (-1);
  fontFamily = deliberate::Settings().value("style/normalfont",fontFamily)
                   .toString();
  deliberate::Settings().setValue ("style/normalfont",fontFamily);
  if (fontFamily == "default") {
    fontFamily = defaultFamily;
  }
  pointSize = deliberate::Settings().value ("style/normalpointsize",pointSize)
                   .toInt ();
  deliberate::Settings().setValue ("style/normalpointsize",pointSize);
  if (pointSize < 0) {
    pointSize = QFont().pointSize();
  }
  app.setFont (QFont (fontFamily, pointSize));
#endif
  bool isPhone = opts.SeenOpt("phone");
  if (isPhone) {
    QFont font = app.font();
    font.setPointSize(font.pointSize()+6);
    app.setFont(font);
  }
  qDebug () << " setting point size to " << app.font().pointSize();
  chatmain.Init (&app,isPhone);
  chatmain.setWindowTitle (egalite::Magic::Name);
  app.setWindowIcon (chatmain.windowIcon());

  chatmain.AddConfigMessages (configMessages);

  chatmain.Run ();
  int result = app.exec ();
  qDebug () << " application returns " << result;
}
예제 #21
0
파일: jacobi3d.C 프로젝트: luyukunphy/namd
    Main(CkArgMsg* m) {
        if ( (m->argc != 3) && (m->argc != 7) ) {
            CkPrintf("%s [array_size] [block_size]\n", m->argv[0]);
            CkPrintf("OR %s [array_size_X] [array_size_Y] [array_size_Z] [block_size_X] [block_size_Y] [block_size_Z]\n", m->argv[0]);
            CkAbort("Abort");
        }

        // set iteration counter to zero
        iterations = 0;

        // store the main proxy
        mainProxy = thisProxy;

        if(m->argc == 3) {
            arrayDimX = arrayDimY = arrayDimZ = atoi(m->argv[1]);
            blockDimX = blockDimY = blockDimZ = atoi(m->argv[2]);
        }
        else if (m->argc == 7) {
            arrayDimX = atoi(m->argv[1]);
            arrayDimY = atoi(m->argv[2]);
            arrayDimZ = atoi(m->argv[3]);
            blockDimX = atoi(m->argv[4]);
            blockDimY = atoi(m->argv[5]);
            blockDimZ = atoi(m->argv[6]);
        }

        if (arrayDimX < blockDimX || arrayDimX % blockDimX != 0)
            CkAbort("array_size_X % block_size_X != 0!");
        if (arrayDimY < blockDimY || arrayDimY % blockDimY != 0)
            CkAbort("array_size_Y % block_size_Y != 0!");
        if (arrayDimZ < blockDimZ || arrayDimZ % blockDimZ != 0)
            CkAbort("array_size_Z % block_size_Z != 0!");

        num_chare_x = arrayDimX / blockDimX;
        num_chare_y = arrayDimY / blockDimY;
        num_chare_z = arrayDimZ / blockDimZ;

        // print info
        CkPrintf("\nSTENCIL COMPUTATION WITH NO BARRIERS\n");
        CkPrintf("Running Jacobi on %d processors with (%d, %d, %d) chares\n", CkNumPes(), num_chare_x, num_chare_y, num_chare_z);
        CkPrintf("Array Dimensions: %d %d %d\n", arrayDimX, arrayDimY, arrayDimZ);
        CkPrintf("Block Dimensions: %d %d %d\n", blockDimX, blockDimY, blockDimZ);

        // Create new array of worker chares
#if USE_TOPOMAP
        CProxy_JacobiMap map = CProxy_JacobiMap::ckNew(num_chare_x, num_chare_y, num_chare_z);
        CkPrintf("Topology Mapping is being done ... \n");
        CkArrayOptions opts(num_chare_x, num_chare_y, num_chare_z);
        opts.setMap(map);
        array = CProxy_Jacobi::ckNew(opts);
#else
        array = CProxy_Jacobi::ckNew(num_chare_x, num_chare_y, num_chare_z);
#endif

        TopoManager tmgr;
        CkArray *jarr = array.ckLocalBranch();
        int jmap[num_chare_x][num_chare_y][num_chare_z];

        int hops=0, p;
        for(int i=0; i<num_chare_x; i++)
            for(int j=0; j<num_chare_y; j++)
                for(int k=0; k<num_chare_z; k++) {
                    jmap[i][j][k] = jarr->procNum(CkArrayIndex3D(i, j, k));
                }

        for(int i=0; i<num_chare_x; i++)
            for(int j=0; j<num_chare_y; j++)
                for(int k=0; k<num_chare_z; k++) {
                    p = jmap[i][j][k];
                    hops += tmgr.getHopsBetweenRanks(p, jmap[wrap_x(i+1)][j][k]);
                    hops += tmgr.getHopsBetweenRanks(p, jmap[wrap_x(i-1)][j][k]);
                    hops += tmgr.getHopsBetweenRanks(p, jmap[i][wrap_y(j+1)][k]);
                    hops += tmgr.getHopsBetweenRanks(p, jmap[i][wrap_y(j-1)][k]);
                    hops += tmgr.getHopsBetweenRanks(p, jmap[i][j][wrap_z(k+1)]);
                    hops += tmgr.getHopsBetweenRanks(p, jmap[i][j][wrap_z(k-1)]);
                }
        CkPrintf("Total Hops: %d\n", hops);

#ifdef JACOBI_OPENMP
        CProxy_OmpInitializer ompInit =
            CProxy_OmpInitializer::ckNew(4);
#else
        //Start the computation
        start();
#endif
    }
예제 #22
0
void PipelineFlowChart::paintEvent(QPaintEvent *e)
{
  if(m_StageNames.empty())
    return;

  QPainter p(this);

  p.fillRect(rect(), Qt::transparent);

  p.setRenderHint(QPainter::Antialiasing, true);

  const QRectF totalRect = totalAreaRect();
  const QRectF box0Rect = boxRect(0);

  const qreal radius = qMin(MaxBoxCornerRadius, box0Rect.height() * BoxCornerRadiusFraction);

  const qreal arrowY = totalRect.y() + totalRect.height() / 2;

  QColor base = palette().color(QPalette::Base);
  QColor baseText = palette().color(QPalette::Text);
  QColor inactiveWin = palette().color(QPalette::Inactive, QPalette::Dark);
  QColor inactiveWinText = palette().color(QPalette::Inactive, QPalette::WindowText);
  QColor tooltip = palette().color(QPalette::ToolTipBase);
  QColor tooltipText = palette().color(QPalette::ToolTipText);

  QPen pen(baseText);
  QPen selectedPen(Qt::red);

  int num = numGaps();
  for(int i = 0; i < num; i++)
  {
    if(!m_StageFlows[i] || !m_StageFlows[i + 1])
      continue;

    float right = totalRect.x() + (i + 1) * (box0Rect.width() + boxMargin());
    float left = right - boxMargin();

    p.setBrush(baseText);
    drawArrow(p, pen, ArrowHeadSize, arrowY, left, right);
  }

  num = numItems();
  for(int i = 0; i < num; i++)
  {
    QRectF boxrect = boxRect(i);

    QBrush backBrush(base);
    QPen textPen(baseText);
    QPen outlinePen = pen;

    if(!stageEnabled(i))
    {
      backBrush.setColor(inactiveWin);
      textPen.setColor(inactiveWinText);
    }

    if(i == m_HoverStage)
    {
      backBrush.setColor(tooltip);
      textPen.setColor(tooltipText);
    }

    if(i == m_SelectedStage)
    {
      outlinePen = selectedPen;
    }

    outlinePen.setWidthF(BoxBorderWidth);

    p.setPen(outlinePen);
    p.setBrush(backBrush);
    p.drawRoundedRect(boxrect, radius, radius);

    QTextOption opts(Qt::AlignCenter);
    opts.setWrapMode(QTextOption::NoWrap);

    QString s = m_StageNames[i];

    QRectF reqBox = p.boundingRect(QRectF(0, 0, 1, 1), m_StageNames[i], opts);

    if(reqBox.width() + BoxLabelMargin > (float)boxrect.width())
      s = m_StageAbbrevs[i];

    p.setPen(textPen);
    p.drawText(boxrect, s, opts);
  }
}
예제 #23
0
int main(int argc, char **argv) {
  unsigned int num_pts = 100;
  unsigned int num_pairs = num_pts / 2.0;
  const double alpha = 3.0;
  const double beta = 10.0;
  const double obs_stddev = 1e-3;

  MPI_Init(&argc, &argv);

  QUESO::FullEnvironment env(MPI_COMM_WORLD, "infinite_dim/inverse_options", "", NULL);

  libMesh::LibMeshInit init(argc, argv);

  // Generate the mesh on which the samples live.
  libMesh::Mesh mesh;
  libMesh::MeshTools::Generation::build_line(mesh, num_pts, 0.0, 1.0, EDGE2);

  // Use a helper object to define some of the properties of our samples
  QUESO::FunctionOperatorBuilder fobuilder;
  fobuilder.order = "FIRST";
  fobuilder.family = "LAGRANGE";
  fobuilder.num_req_eigenpairs = num_pairs;

  // Define the mean of the prior
  QUESO::LibMeshFunction mean(fobuilder, mesh);

  // Define the precision operator of the prior
  QUESO::LibMeshNegativeLaplacianOperator precision(fobuilder, mesh);

  // Define the prior measure
  QUESO::InfiniteDimensionalGaussian mu(env, mean, precision, alpha, beta);

  // Create likelihood object
  Likelihood llhd(obs_stddev);

  // The worst hack in the world ever
  // boost::shared_ptr<LibMeshFunction> lm_draw(boost::static_pointer_cast<LibMeshFunction>(mu.draw()));
  // std::cout << "before zero" << std::endl;
  // lm_draw->equation_systems->get_system<ExplicitSystem>("Function").solution->zero();
  // std::cout << "after zero" << std::endl;

  // Create the options helper object that determines what options to pass to
  // the sampler
  QUESO::InfiniteDimensionalMCMCSamplerOptions opts(env, "");

  // Set the number of iterations to do
  opts.m_num_iters = 1000;

  // Set the frequency with which we save samples
  opts.m_save_freq = 10;

  // Set the RWMH step size
  opts.m_rwmh_step = 0.1;

  // Construct the sampler, and set the name of the output file (will only
  // write HDF5 files)
  QUESO::InfiniteDimensionalMCMCSampler s(env, mu, llhd, &opts);

  for (unsigned int i = 0; i < opts.m_num_iters; i++) {
    s.step();
    if (i % 100 == 0) {
      std::cout << "sampler iteration: " << i << std::endl;
      std::cout << "avg acc prob is: " << s.avg_acc_prob() << std::endl;
      std::cout << "l2 norm is: " << s.llhd_val() << std::endl;
    }
  }

  return 0;
}
예제 #24
0
void Test::testNormalUsage() {
    {
        AppOptions opts("myapp -b --uintopt 4 -s foo tit 1 tei 6");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        options.parse();
        EXPECT_EQUAL(true, options.boolOpt);
        EXPECT_EQUAL(true, options.boolWithDefOpt);
        EXPECT_EQUAL(5, options.intOpt);
        EXPECT_EQUAL(4u, options.uintOpt);
        EXPECT_APPROX(4, options.floatOpt, 0.00001);
        EXPECT_EQUAL("foo", options.stringOpt);
        EXPECT_EQUAL("tit", options.argString);
        EXPECT_EQUAL(1, options.argInt);
        EXPECT_EQUAL("tei", options.argOptionalString);
        EXPECT_EQUAL(0u, options.properties.size());
        EXPECT_EQUAL(6, options.anotherOptionalArg);
    }
    {
        AppOptions opts("myapp --uintopt 6 tit 1");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        options.parse();
        EXPECT_EQUAL(false, options.boolOpt);
        EXPECT_EQUAL(true, options.boolWithDefOpt);
        EXPECT_EQUAL(5, options.intOpt);
        EXPECT_EQUAL(6u, options.uintOpt);
        EXPECT_APPROX(4, options.floatOpt, 0.00001);
        EXPECT_EQUAL("ballalaika", options.stringOpt);
        EXPECT_EQUAL("tit", options.argString);
        EXPECT_EQUAL(1, options.argInt);
        EXPECT_EQUAL("foo", options.argOptionalString);
        EXPECT_EQUAL(0u, options.properties.size());
        EXPECT_EQUAL(3, options.anotherOptionalArg);
    }
        // Arguments coming after options.
        // (Required for nesting of short options)
    {
        AppOptions opts("myapp --uintopt --intopt 6 -8 tit 1 tei");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        options.parse();
        EXPECT_EQUAL(false, options.boolOpt);
        EXPECT_EQUAL(true, options.boolWithDefOpt);
        EXPECT_EQUAL(-8, options.intOpt);
        EXPECT_EQUAL(6u, options.uintOpt);
        EXPECT_APPROX(4, options.floatOpt, 0.00001);
        EXPECT_EQUAL("ballalaika", options.stringOpt);
        EXPECT_EQUAL("tit", options.argString);
        EXPECT_EQUAL(1, options.argInt);
        EXPECT_EQUAL("tei", options.argOptionalString);
        EXPECT_EQUAL(0u, options.properties.size());
    }
    {
        AppOptions opts( "myapp -uib 6 -8 --boolwithdef tit 1 tei");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        options.parse();
        EXPECT_EQUAL(true, options.boolOpt);
        EXPECT_EQUAL(false, options.boolWithDefOpt);
        EXPECT_EQUAL(-8, options.intOpt);
        EXPECT_EQUAL(6u, options.uintOpt);
        EXPECT_APPROX(4, options.floatOpt, 0.00001);
        EXPECT_EQUAL("ballalaika", options.stringOpt);
        EXPECT_EQUAL("tit", options.argString);
        EXPECT_EQUAL(1, options.argInt);
        EXPECT_EQUAL("tei", options.argOptionalString);
        EXPECT_EQUAL(0u, options.properties.size());
    }
        // Properties
    {
        AppOptions opts("myapp -u 6 -p foo bar --prop hmm brr tit 1 tei");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        options.parse();
        EXPECT_EQUAL(false, options.boolOpt);
        EXPECT_EQUAL(true, options.boolWithDefOpt);
        EXPECT_EQUAL(5, options.intOpt);
        EXPECT_EQUAL(6u, options.uintOpt);
        EXPECT_APPROX(4, options.floatOpt, 0.00001);
        EXPECT_EQUAL("ballalaika", options.stringOpt);
        EXPECT_EQUAL("tit", options.argString);
        EXPECT_EQUAL(1, options.argInt);
        EXPECT_EQUAL("tei", options.argOptionalString);
        EXPECT_EQUAL(2u, options.properties.size());
        EXPECT_EQUAL("bar", options.properties["foo"]);
        EXPECT_EQUAL("brr", options.properties["hmm"]);
    }
}
예제 #25
0
        Client::Client(Socket &_socket, HWND _wnd, HINSTANCE _instance, unsigned int _screenWidth, unsigned int _screenHeight, bool _isWindowed) :
        sock(_socket), normalFont(512, 256, 32, 32, 32), currentState(nullptr), time(0), wnd(_wnd), screenWidth(_screenWidth), 
                screenHeight(_screenHeight), isWindowed(_isWindowed), isRunning(true), textureManager(nullptr), directInput(nullptr), direct3D(nullptr), xAudio(nullptr),
                tabClickSFX(-1), errorSFX(-1), acceptedSFX(-1), backImgID(-1), splash(false), timer(0), splashScreen(-1), splashMusicID(-1)
        {
                //Seed Rand
                srand((unsigned int)::time(0));

                /* Acquire the lame SGD singleton instances. */
                textureManager = CSGD_TextureManager::GetInstance();
                directInput = CSGD_DirectInput::GetInstance();
                direct3D = CSGD_Direct3D::GetInstance();
                xAudio = CSGD_XAudio2::GetInstance();

                /* Initialize the SGD wrappers. */
                direct3D->InitDirect3D(wnd, screenWidth, screenHeight, isWindowed, false);
                textureManager->InitTextureManager(direct3D->GetDirect3DDevice(), direct3D->GetSprite());
                directInput->InitDirectInput(wnd, _instance, DI_KEYBOARD | DI_MOUSE | DI_JOYSTICKS);
                xAudio->InitXAudio2();

                /* Read in user options. */
                std::ifstream opts((getAppDataFolder() + "client\\options").c_str(), std::ios_base::binary | std::ios_base::in);
                if(opts.is_open())
                {
                        float volumes[2] = { 0.0f, 0.0f };
                        bool fullscreen = false;

                        /* Read in the volumes and close the file. */
                        opts.read((char*)volumes, sizeof(volumes));
                        opts.read((char*)&fullscreen, sizeof(fullscreen));
                        opts.close();

                        /* Set the volumes. */
                        xAudio->MusicSetMasterVolume(volumes[0]);
                        xAudio->SFXSetMasterVolume(volumes[1]);

                        /* Set the fullscreen settings. */
                        setIsWindowed(!fullscreen);
                }

                /* Set the localhost address. */
                localhost.setAddress("127.0.0.1");
                localhost.setPort(CLIENT_PORT);

                /* Set the server address. */
                server.setPort(SERVER_PORT);

                /* Disable both the Direct3D and the Windows cursor in our window. */
                direct3D->GetDirect3DDevice()->ShowCursor(false);
                ShowCursor(true);

                //When the Client start it goes straight to the Main Menu State
                MainMenuState* mainMenu = new MainMenuState(*this);
                PushState(mainMenu);

                /* Load the normal font. */
                normalFont.loadTexture(_T("resources/fonts/test2.png"));

                /* Load the hud image and potions. */
                gameplayImgID = textureManager->LoadTexture(_T("resources/hud/HUD_assets.png"));

                /* Load the menu image. */
                menuImgID = textureManager->LoadTexture(_T("resources/menus/menu&HUD.png"));

                //Load the styalized background image
                backImgID = textureManager->LoadTexture(_T("resources/world/graphics/World_map1.png"));

                /* The Loading of the world tile image is handled in worldMap. */
                worldImgID = -1;

                server.setPort(SERVER_PORT);

                //Load the Sound Effects
                buttonClickSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/menu/buttonClick.wav"));
                tabClickSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/menu/tabClick.wav"));
                errorSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/menu/warningBeep.wav"));
                acceptedSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/menu/acceptedBeep.wav"));

                //Load Spell Sound Effects
                fireballSFX        = xAudio->SFXLoadSound(_T("resources/audio/sfx/spells/fireball.wav"));    
                healSFX            = xAudio->SFXLoadSound(_T("resources/audio/sfx/spells/heal.wav"));  
                iceballSFX         = xAudio->SFXLoadSound(_T("resources/audio/sfx/spells/iceball.wav"));  
                aoeFireballSFX     = xAudio->SFXLoadSound(_T("resources/audio/sfx/spells/aoeFireball.wav"));  
                diabloSFX          = xAudio->SFXLoadSound(_T("resources/audio/sfx/spells/diablo.wav"));  
                frostbiteSFX       = xAudio->SFXLoadSound(_T("resources/audio/sfx/spells/frostbite.wav"));  
                glacialSpikeSFX    = xAudio->SFXLoadSound(_T("resources/audio/sfx/spells/glacialSpike.wav"));  
                lightningBoltSFX   = xAudio->SFXLoadSound(_T("resources/audio/sfx/spells/lightningBolt.wav"));  
                lightningStrikeSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/spells/lightningStrike.wav"));  
                phoenixSFX         = xAudio->SFXLoadSound(_T("resources/audio/sfx/spells/phoenix.wav"));  
                valkyrieSFX        = xAudio->SFXLoadSound(_T("resources/audio/sfx/spells/valkyrie.wav"));  
               

                //load music
                backgroundMusicID = xAudio->MusicLoadSong(_T("resources/audio/DayGloomy.xwm"));
                splashMusicID = xAudio->MusicLoadSong(_T("resources/audio/Intro.xwm"));


                //Play music
                xAudio->MusicPlaySong(splashMusicID, false);

                //Display Splash Screen
                splash = true;
                timer = 5.0f;

                //Load Splash Screen
                splashScreen = textureManager->LoadTexture(_T("resources/hud/darkRedemptionLogo.png"));

                inventorySelectionSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/menu/inventorySelection.wav"));
                potionSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/world/potion.wav"));
                deathSFX  = xAudio->SFXLoadSound(_T("resources/audio/sfx/character/death1.wav"));
                goldSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/world/gold.wav"));
                gemSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/world/gem.wav"));
                pickUpSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/character/pickup.wav"));
                getHitSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/character/gethit.wav")); 
                enemyGetHitSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/enemies/gethit1.wav"));
                enemyGrowlerHitSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/enemies/gethit3.wav"));
                levelUpSFX = xAudio->SFXLoadSound(_T("resources/audio/sfx/character/levelup.wav"));

#if PLATFORM_ARCADE
                setIsWindowed(false);
#endif

        }
예제 #26
0
void Test::testFailures() {
        // Non-existing long option
    {
        AppOptions opts("myapp -b --uintopt 4 -s foo --none");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        try{
            options.parse();
            TEST_FATAL("Expected exception");
        } catch (InvalidCommandLineArgumentsException& e) {
            EXPECT_EQUAL("Invalid option 'none'.", e.getMessage());
        }
    }
        // Non-existing short option
    {
        AppOptions opts("myapp -b --uintopt 4 -s foo -q");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        try{
            options.parse();
            TEST_FATAL("Expected exception");
        } catch (InvalidCommandLineArgumentsException& e) {
            EXPECT_EQUAL("Invalid option 'q'.", e.getMessage());
        }
    }
        // Lacking option argument
    {
        AppOptions opts("myapp -b --uintopt 4 -s");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        try{
            options.parse();
            TEST_FATAL("Expected exception");
        } catch (InvalidCommandLineArgumentsException& e) {
            EXPECT_EQUAL("Option 's' needs 1 arguments. Only 0 available.",
                       e.getMessage());
        }
    }
        // Out of signed ranged
    {
        AppOptions opts("myapp -b --uintopt 4 -intopt 3000000000");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        try{
            options.parse();
            TEST_FATAL("Expected exception");
        } catch (InvalidCommandLineArgumentsException& e) {
            EXPECT_EQUAL("The argument '3000000000' can not be interpreted as a "
                       "number of type int.", e.getMessage());
        }
    }
        // Negative value to unsigned var (Currently doesnt fail)
/*
    {
        AppOptions opts("myapp -b --uintopt -1 foo 0");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        try{
            options.parse();
            TEST_FATAL("Expected exception");
        } catch (InvalidCommandLineArgumentsException& e) {
            EXPECT_EQUAL("The argument '-1' can not be interpreted as a "
                         "number of type uint.", e.getMessage());
        }
    }
    */
        // Lacking required option
    {
        AppOptions opts("myapp -b");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        try{
            options.parse();
            TEST_FATAL("Expected exception");
        } catch (InvalidCommandLineArgumentsException& e) {
            EXPECT_EQUAL("Option 'uintopt' has no default and must be set.",
                       e.getMessage());
        }
    }
        // Lacking required argument
    {
        AppOptions opts("myapp --uintopt 1 tit");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        try{
            options.parse();
            TEST_FATAL("Expected exception");
        } catch (InvalidCommandLineArgumentsException& e) {
            EXPECT_EQUAL("Insufficient data is given to set required argument "
                       "'argInt'.",
                       e.getMessage());
        }
    }
        // Argument of wrong type
    {
        AppOptions opts("myapp --uintopt 1 tit en");
        MyOptions options(opts.getArgCount(), opts.getArguments());
        try{
            options.parse();
            TEST_FATAL("Expected exception");
        } catch (InvalidCommandLineArgumentsException& e) {
            EXPECT_EQUAL("The argument 'en' can not be interpreted as a number "
                       "of type int.",
                       e.getMessage());
        }
    }
}
예제 #27
0
/* ////////////////////////////////////////////////////////////////////////////
   -- Testing zgetri_batched
*/
int main( int argc, char** argv)
{
    TESTING_INIT();

    // constants
    const magmaDoubleComplex c_zero    = MAGMA_Z_ZERO;
    const magmaDoubleComplex c_one     = MAGMA_Z_ONE;
    const magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE;
    
    real_Double_t   gflops, gpu_perf, gpu_time, cpu_perf, cpu_time;
    magmaDoubleComplex *h_A, *h_Ainv, *h_R, *work;
    magmaDoubleComplex_ptr d_A, d_invA;
    magmaDoubleComplex_ptr *dA_array;
    magmaDoubleComplex_ptr *dinvA_array;
    magma_int_t **dipiv_array;
    magma_int_t *dinfo_array;
    magma_int_t *ipiv, *cpu_info;
    magma_int_t *d_ipiv, *d_info;
    magma_int_t N, n2, lda, ldda, info, info1, info2, lwork;
    magma_int_t ione     = 1;
    magma_int_t ISEED[4] = {0,0,0,1};
    magmaDoubleComplex tmp;
    double  error, rwork[1];
    magma_int_t columns;
    magma_int_t status = 0;
    
    magma_opts opts( MagmaOptsBatched );
    opts.parse_opts( argc, argv );
    
    magma_int_t batchCount = opts.batchcount;
    double tol = opts.tolerance * lapackf77_dlamch("E");

    printf("%% batchCount   N    CPU Gflop/s (ms)    GPU Gflop/s (ms)   ||I - A*A^{-1}||_1 / (N*cond(A))\n");
    printf("%%===============================================================================\n");
    for( int itest = 0; itest < opts.ntest; ++itest ) {    
        for( int iter = 0; iter < opts.niter; ++iter ) {
            N = opts.nsize[itest];
            lda    = N;
            n2     = lda*N * batchCount;
            ldda   = magma_roundup( N, opts.align );  // multiple of 32 by default
            // This is the correct flops but since this getri_batched is based on
            // 2 trsm = getrs and to know the real flops I am using the getrs one
            //gflops = (FLOPS_ZGETRF( N, N ) + FLOPS_ZGETRI( N ))/ 1e9 * batchCount;
            gflops = (FLOPS_ZGETRF( N, N ) + FLOPS_ZGETRS( N, N ))/ 1e9 * batchCount;

            // query for workspace size
            lwork = -1;
            lapackf77_zgetri( &N, NULL, &lda, NULL, &tmp, &lwork, &info );
            if (info != 0) {
                printf("lapackf77_zgetri returned error %d: %s.\n",
                       (int) info, magma_strerror( info ));
            }
            lwork = magma_int_t( MAGMA_Z_REAL( tmp ));
            
            TESTING_MALLOC_CPU( cpu_info, magma_int_t,        batchCount );
            TESTING_MALLOC_CPU( ipiv,     magma_int_t,        N * batchCount );
            TESTING_MALLOC_CPU( work,     magmaDoubleComplex, lwork*batchCount );
            TESTING_MALLOC_CPU( h_A,      magmaDoubleComplex, n2     );
            TESTING_MALLOC_CPU( h_Ainv,   magmaDoubleComplex, n2     );
            TESTING_MALLOC_CPU( h_R,      magmaDoubleComplex, n2     );
            
            TESTING_MALLOC_DEV( d_A,      magmaDoubleComplex, ldda*N * batchCount );
            TESTING_MALLOC_DEV( d_invA,   magmaDoubleComplex, ldda*N * batchCount );
            TESTING_MALLOC_DEV( d_ipiv,   magma_int_t,        N * batchCount );
            TESTING_MALLOC_DEV( d_info,   magma_int_t,        batchCount );

            TESTING_MALLOC_DEV( dA_array,    magmaDoubleComplex*, batchCount );
            TESTING_MALLOC_DEV( dinvA_array, magmaDoubleComplex*, batchCount );
            TESTING_MALLOC_DEV( dinfo_array, magma_int_t,         batchCount );
            TESTING_MALLOC_DEV( dipiv_array, magma_int_t*,        batchCount );
            
            /* Initialize the matrix */
            lapackf77_zlarnv( &ione, ISEED, &n2, h_A );
            columns = N * batchCount;
            lapackf77_zlacpy( MagmaFullStr, &N, &columns, h_A, &lda, h_R,  &lda );
            lapackf77_zlacpy( MagmaFullStr, &N, &columns, h_A, &lda, h_Ainv, &lda );
            magma_zsetmatrix( N, columns, h_R, lda, d_A, ldda, opts.queue );

            /* ====================================================================
               Performs operation using MAGMA
               =================================================================== */
            magma_zset_pointer( dA_array, d_A, ldda, 0, 0, ldda * N, batchCount, opts.queue );
            magma_zset_pointer( dinvA_array, d_invA, ldda, 0, 0, ldda * N, batchCount, opts.queue );
            magma_iset_pointer( dipiv_array, d_ipiv, 1, 0, 0, N, batchCount, opts.queue );

            gpu_time = magma_sync_wtime( opts.queue );
            info1 = magma_zgetrf_batched( N, N, dA_array, ldda, dipiv_array, dinfo_array, batchCount, opts.queue);
            info2 = magma_zgetri_outofplace_batched( N, dA_array, ldda, dipiv_array, dinvA_array, ldda, dinfo_array, batchCount, opts.queue);
            gpu_time = magma_sync_wtime( opts.queue ) - gpu_time;
            gpu_perf = gflops / gpu_time;

            // check correctness of results throught "dinfo_magma" and correctness of argument throught "info"
            magma_getvector( batchCount, sizeof(magma_int_t), dinfo_array, 1, cpu_info, 1, opts.queue );
            for (magma_int_t i=0; i < batchCount; i++)
            {
                if (cpu_info[i] != 0 ) {
                    printf("magma_zgetrf_batched matrix %d returned error %d\n", (int) i, (int)cpu_info[i] );
                }
            }
            if (info1 != 0) printf("magma_zgetrf_batched returned argument error %d: %s.\n", (int) info1, magma_strerror( info1 ));
            if (info2 != 0) printf("magma_zgetri_batched returned argument error %d: %s.\n", (int) info2, magma_strerror( info2 ));
            
            /* =====================================================================
               Performs operation using LAPACK
               =================================================================== */
            if ( opts.lapack ) {
                cpu_time = magma_wtime();
                #if !defined (BATCHED_DISABLE_PARCPU) && defined(_OPENMP)
                magma_int_t nthreads = magma_get_lapack_numthreads();
                magma_set_lapack_numthreads(1);
                magma_set_omp_numthreads(nthreads);
                #pragma omp parallel for schedule(dynamic)
                #endif
                for (int i=0; i < batchCount; i++)
                {
                    magma_int_t locinfo;
                    lapackf77_zgetrf(&N, &N, h_Ainv + i*lda*N, &lda, ipiv + i*N, &locinfo);
                    if (locinfo != 0) {
                        printf("lapackf77_zgetrf returned error %d: %s.\n",
                               (int) locinfo, magma_strerror( locinfo ));
                    }
                    lapackf77_zgetri(&N, h_Ainv + i*lda*N, &lda, ipiv + i*N, work + i*lwork, &lwork, &locinfo );
                    if (locinfo != 0) {
                        printf("lapackf77_zgetri returned error %d: %s.\n",
                               (int) locinfo, magma_strerror( locinfo ));
                    }
                }
                #if !defined (BATCHED_DISABLE_PARCPU) && defined(_OPENMP)
                    magma_set_lapack_numthreads(nthreads);
                #endif
                cpu_time = magma_wtime() - cpu_time;
                cpu_perf = gflops / cpu_time;
                
                printf("%10d %5d   %7.2f (%7.2f)   %7.2f (%7.2f)",
                       (int) batchCount, (int) N, cpu_perf, cpu_time*1000., gpu_perf, gpu_time*1000. );
            }
            else {
                printf("%10d %5d     ---   (  ---  )   %7.2f (%7.2f)",
                       (int) batchCount, (int) N, gpu_perf, gpu_time*1000. );
            }
            
            /* =====================================================================
               Check the result
               =================================================================== */
            if ( opts.check ) {
                magma_igetvector( N*batchCount, d_ipiv, 1, ipiv, 1, opts.queue );
                magma_zgetmatrix( N, N*batchCount, d_invA, ldda, h_Ainv, lda, opts.queue );
                error = 0;
                for (magma_int_t i=0; i < batchCount; i++)
                {
                    for (magma_int_t k=0; k < N; k++) {
                        if (ipiv[i*N+k] < 1 || ipiv[i*N+k] > N )
                        {
                            printf("error for matrix %d ipiv @ %d = %d\n", (int) i, (int) k, (int) ipiv[i*N+k]);
                            error = -1;
                        }
                    }
                    if (error == -1) {
                        break;
                    }
                    
                    // compute 1-norm condition number estimate, following LAPACK's zget03
                    double normA, normAinv, rcond, err;
                    normA    = lapackf77_zlange( "1", &N, &N, h_A    + i*lda*N, &lda, rwork );
                    normAinv = lapackf77_zlange( "1", &N, &N, h_Ainv + i*lda*N, &lda, rwork );
                    if ( normA <= 0 || normAinv <= 0 ) {
                        rcond = 0;
                        err = 1 / (tol/opts.tolerance);  // == 1/eps
                    }
                    else {
                        rcond = (1 / normA) / normAinv;
                        // R = I
                        // R -= A*A^{-1}
                        // err = ||I - A*A^{-1}|| / ( N ||A||*||A^{-1}|| ) = ||R|| * rcond / N, using 1-norm
                        lapackf77_zlaset( "full", &N, &N, &c_zero, &c_one, h_R + i*lda*N, &lda );
                        blasf77_zgemm( "no", "no", &N, &N, &N, &c_neg_one,
                                       h_A    + i*lda*N, &lda,
                                       h_Ainv + i*lda*N, &lda, &c_one,
                                       h_R    + i*lda*N, &lda );
                        err = lapackf77_zlange( "1", &N, &N, h_R + i*lda*N, &lda, rwork );
                        err = err * rcond / N;
                    }
                    if ( isnan(err) || isinf(err) ) {
                        error = err;
                        break;
                    }
                    error = max( err, error );
                }
                bool okay = (error < tol);
                status += ! okay;
                printf("   %8.2e   %s\n", error, (okay ? "ok" : "failed") );
            }
            else {
                printf("\n");
            }

            TESTING_FREE_CPU( cpu_info );
            TESTING_FREE_CPU( ipiv   );
            TESTING_FREE_CPU( work   );
            TESTING_FREE_CPU( h_A    );
            TESTING_FREE_CPU( h_Ainv );
            TESTING_FREE_CPU( h_R    );
            
            TESTING_FREE_DEV( d_A );
            TESTING_FREE_DEV( d_invA );
            TESTING_FREE_DEV( d_ipiv );
            TESTING_FREE_DEV( d_info );
            
            TESTING_FREE_DEV( dA_array );
            TESTING_FREE_DEV( dinvA_array );
            TESTING_FREE_DEV( dinfo_array );
            TESTING_FREE_DEV( dipiv_array );
            fflush( stdout );
        }
        if ( opts.niter > 1 ) {
            printf( "\n" );
        }
    }
    
    opts.cleanup();
    TESTING_FINALIZE();
    return status;
}
예제 #28
0
파일: main.cpp 프로젝트: Grazfather/megumi
int main(int argc, char* argv[])
{
  try {
    // parse command line
    po::options_description opts("Options");
    opts.add_options()
        ("help,h", "this help")
        ("gdb-server,g", po::value<int>()->implicit_value(2345), "run a gdbserver on given port")
        ("sys-ticks", po::value<unsigned int>(), "stop after given number of ticks")
        ("conf-file,f", po::value<std::string>(), "configuration file")
        ;

    po::options_description opts_hidden; // hidden
    opts_hidden.add_options()
        ("input-file", po::value<std::string>(), "input file")
        ;
    po::positional_options_description popts;
    popts.add("input-file", 1);

    po::options_description opts_all;
    opts_all.add(opts).add(opts_hidden);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv)
              .options(opts_all).positional(popts).run(), vm);
    po::notify(vm);

    // process command line parameters
    if(vm.count("help")) {
      usage(argv[0], opts);
      return 0;
    } else if(vm.count("input-file") == 0) {
      std::cerr << "missing input file" << std::endl;
      return 1;
    }

    pt::ptree ptconf;
    if(vm.count("conf-file")) {
      std::string fname = vm["conf-file"].as<std::string>();
      pt::ini_parser::read_ini(fname, ptconf);
    }

    Log::setMinimumSeverity(Log::INFO);
    LOG(NOTICE) << "logging start";

    model::ATxmega128A1 device(ptconf);
    DLOG(NOTICE) << "device created";
    std::vector<uint8_t> progdata = parse_hex_file(vm["input-file"].as<std::string>());
    device.loadFlash(progdata);
    DLOG(NOTICE) << "flash data loaded";
    device.reset();

    if(vm.count("gdb-server")) {
      if(vm.count("sys-ticks")) {
        std::cerr << "--gdb-server and --sys-ticks are incompatible" << std::endl;
        return 1;
      }
      GdbServer gdbserver(&device);
      gdbserver.run(vm["gdb-server"].as<int>());
    } else if(vm.count("sys-ticks")) {
      unsigned int ticks = vm["sys-ticks"].as<unsigned int>();
      while(device.clk_sys_tick() < ticks) {
        device.step();
      }
    } else {
      for(;;) {
        device.step();
      }
    }

  } catch(const std::exception& e) {
    std::cerr << "error: " << e.what() << std::endl;
    return 1;
  } catch(...) {
    std::cerr << "unknown error" << std::endl;
  }
}
예제 #29
0
파일: cmdline.cpp 프로젝트: mhdsedighi/SOFA
bool CmdLine::parse(int argc, char** argv, bool* error)
{
  // First create the list of options
  int nopts = opts().size();
  struct option* options = new struct option[nopts+1];
  std::string shortoptions;
  for (int i=0;i<nopts;i++)
  {
    options[i].name = opts()[i]->longname;
    options[i].has_arg = opts()[i]->arg;
    options[i].flag = NULL;
    options[i].val = 256+i;
    if (opts()[i]->shortname!='\0')
    {
      shortoptions+=opts()[i]->shortname;
      if (opts()[i]->arg == BaseOption::REQ_ARG)
	shortoptions+=':';
      else if (opts()[i]->arg == BaseOption::OPT_ARG)
	shortoptions+="::";
    }
  }
  options[nopts].name = NULL;
  options[nopts].has_arg = 0;
  options[nopts].flag = NULL;
  options[nopts].val = 0;

  //std::cerr << "ShortOptions: "<<shortoptions<<std::endl;

  int option_index = -1;
  int c;

  const char* program = strrchr(argv[0],'/');
  if (program != NULL) ++program;
  else program = argv[0];

#if !defined(__APPLE__)
  while( (c = getopt_long_only(argc,argv,shortoptions.data(),options,&option_index)) != -1)
#else
  while( (c = getopt_long(argc,argv,shortoptions.data(),options,&option_index)) != -1)
#endif
  {
    if (c=='?' || c==':')
    {
      if (error!=NULL) *error = true;
      return false;
    }
    bool longopt = true;
    if (c!=0 && (unsigned)option_index>=(unsigned)nopts)
    {
      longopt = false;
      for (int i=0;i<nopts;i++)
        if (opts()[i]->shortname==c)
	{
	  option_index = i;
	  break;
	}
    }
    if ((unsigned)option_index>=(unsigned)nopts)
    {
      std::cerr<<"Error parsing options"<<std::endl;
      if (error!=NULL) *error = true;
      return false;
    }

    BaseOption* opt = opts()[option_index];

    if (optarg && *optarg)
    {
      if (opt->arg == BaseOption::NO_ARG)
      {
	std::cerr << program << ": option ";
	if (longopt) std::cerr << "--"<<opt->longname;
	else         std::cerr << '-'<<opt->shortname;
	std::cerr << " requires no value while \""<<optarg<<"\" was specified."<<std::endl;
	if (error!=NULL) *error = true;
	return false;
      }
      else
      {
	if (!opt->set(optarg))
	{
	  std::cerr << program << ": incorrect value for option ";
	  if (longopt) std::cerr << "--"<<opt->longname;
	  else         std::cerr << "-"<<opt->shortname;
	  std::cerr << " .\n";
	  if (error!=NULL) *error = true;
	  return false;
	}
      }
    }
    else
    {
      if (opt->arg == BaseOption::REQ_ARG)
      {
	std::cerr << program << ": option ";
	if (longopt) std::cerr << "--"<<opt->longname;
	else         std::cerr << '-'<<opt->shortname;
	std::cerr << " requires a value."<<std::endl;
	if (error!=NULL) *error = true;
	return false;
      }
      else
      {
	if (!opt->set())
	{
	  std::cerr << program << ": error while treating option ";
	  if (longopt) std::cerr << "--"<<opt->longname;
	  else         std::cerr << '-'<<opt->shortname;
	  std::cerr << " .\n";
	  if (error!=NULL) *error = true;
	  return false;
	}
      }
    }
    option_index=-1;
  }
  for (int i=optind;i<argc;i++)
  {
    args.push_back(argv[i]);
  }
  if (error!=NULL) *error = false;
  if (helpoption!=NULL && helpoption->count>0)
  {
    if (description==NULL) std::cout << program<< "\n";
    std::cout << help() << std::endl;
    return false;
  }
  return true;
}
예제 #30
0
/* ////////////////////////////////////////////////////////////////////////////
   -- Testing slacpy_batched
   Code is very similar to testing_sgeadd_batched.cpp
*/
int main( int argc, char** argv)
{
    TESTING_INIT();

    real_Double_t    gbytes, gpu_perf, gpu_time, cpu_perf, cpu_time;
    float           error, work[1];
    float  c_neg_one = MAGMA_S_NEG_ONE;
    float *h_A, *h_B;
    magmaFloat_ptr d_A, d_B;
    float **hAarray, **hBarray, **dAarray, **dBarray;
    magma_int_t M, N, mb, nb, size, lda, ldda, mstride, nstride, ntile;
    magma_int_t ione     = 1;
    magma_int_t ISEED[4] = {0,0,0,1};
    magma_int_t status = 0;
    
    magma_opts opts( MagmaOptsBatched );
    opts.parse_opts( argc, argv );

    mb = (opts.nb == 0 ? 32 : opts.nb);
    nb = (opts.nb == 0 ? 64 : opts.nb);
    mstride = 2*mb;
    nstride = 3*nb;
    
    printf("%% mb=%d, nb=%d, mstride=%d, nstride=%d\n", (int) mb, (int) nb, (int) mstride, (int) nstride );
    printf("%%   M     N ntile    CPU Gflop/s (ms)    GPU Gflop/s (ms)   check\n");
    printf("%%================================================================\n");
    for( int itest = 0; itest < opts.ntest; ++itest ) {
        for( int iter = 0; iter < opts.niter; ++iter ) {
            M = opts.msize[itest];
            N = opts.nsize[itest];
            lda    = M;
            ldda   = magma_roundup( M, opts.align );  // multiple of 32 by default
            size   = lda*N;
            
            if ( N < nb || M < nb ) {
                ntile = 0;
            } else {
                ntile = min( (M - nb)/mstride + 1,
                             (N - nb)/nstride + 1 );
            }
            gbytes = 2.*mb*nb*ntile / 1e9;
            
            TESTING_MALLOC_CPU( h_A, float, lda *N );
            TESTING_MALLOC_CPU( h_B, float, lda *N );
            TESTING_MALLOC_DEV( d_A, float, ldda*N );
            TESTING_MALLOC_DEV( d_B, float, ldda*N );
            
            TESTING_MALLOC_CPU( hAarray, float*, ntile );
            TESTING_MALLOC_CPU( hBarray, float*, ntile );
            TESTING_MALLOC_DEV( dAarray, float*, ntile );
            TESTING_MALLOC_DEV( dBarray, float*, ntile );
            
            lapackf77_slarnv( &ione, ISEED, &size, h_A );
            lapackf77_slarnv( &ione, ISEED, &size, h_B );

            /* ====================================================================
               Performs operation using MAGMA
               =================================================================== */
            magma_ssetmatrix( M, N, h_A, lda, d_A, ldda );
            magma_ssetmatrix( M, N, h_B, lda, d_B, ldda );
            
            // setup pointers
            for( magma_int_t tile = 0; tile < ntile; ++tile ) {
                magma_int_t offset = tile*mstride + tile*nstride*ldda;
                hAarray[tile] = &d_A[offset];
                hBarray[tile] = &d_B[offset];
            }
            magma_setvector( ntile, sizeof(float*), hAarray, 1, dAarray, 1 );
            magma_setvector( ntile, sizeof(float*), hBarray, 1, dBarray, 1 );
            
            gpu_time = magma_sync_wtime( opts.queue );
            magmablas_slacpy_batched( MagmaFull, mb, nb, dAarray, ldda, dBarray, ldda, ntile, opts.queue );
            gpu_time = magma_sync_wtime( opts.queue ) - gpu_time;
            gpu_perf = gbytes / gpu_time;
            
            /* =====================================================================
               Performs operation using LAPACK
               =================================================================== */
            cpu_time = magma_wtime();
            for( magma_int_t tile = 0; tile < ntile; ++tile ) {
                magma_int_t offset = tile*mstride + tile*nstride*lda;
                lapackf77_slacpy( MagmaFullStr, &mb, &nb,
                                  &h_A[offset], &lda,
                                  &h_B[offset], &lda );
            }
            cpu_time = magma_wtime() - cpu_time;
            cpu_perf = gbytes / cpu_time;
            
            /* =====================================================================
               Check the result
               =================================================================== */
            magma_sgetmatrix( M, N, d_B, ldda, h_A, lda );
            
            blasf77_saxpy(&size, &c_neg_one, h_A, &ione, h_B, &ione);
            error = lapackf77_slange("f", &M, &N, h_B, &lda, work);
            bool okay = (error == 0);
            status += ! okay;

            printf("%5d %5d %5d   %7.2f (%7.2f)   %7.2f (%7.2f)   %s\n",
                   (int) M, (int) N, (int) ntile,
                   cpu_perf, cpu_time*1000., gpu_perf, gpu_time*1000.,
                   (okay ? "ok" : "failed") );
            
            TESTING_FREE_CPU( h_A );
            TESTING_FREE_CPU( h_B );
            TESTING_FREE_DEV( d_A );
            TESTING_FREE_DEV( d_B );
            
            TESTING_FREE_CPU( hAarray );
            TESTING_FREE_CPU( hBarray );
            TESTING_FREE_DEV( dAarray );
            TESTING_FREE_DEV( dBarray );
            fflush( stdout );
        }
        if ( opts.niter > 1 ) {
            printf( "\n" );
        }
    }

    opts.cleanup();
    TESTING_FINALIZE();
    return status;
}