コード例 #1
0
ファイル: Constraint.cpp プロジェクト: lanigb/FreeCAD
Constraint::Constraint()
: Value(0.0),
  Type(None),
  AlignmentType(Undef),
  Name(""),
  First(GeoUndef),
  FirstPos(none),
  Second(GeoUndef),
  SecondPos(none),
  Third(GeoUndef),
  ThirdPos(none),
  LabelDistance(10.f),
  LabelPosition(0.f),
  isDriving(true),
  InternalAlignmentIndex(-1),
  isInVirtualSpace(false)
{
    // Initialize a random number generator, to avoid Valgrind false positives.
    static boost::mt19937 ran;
    static bool seeded = false;

    if (!seeded) {
        ran.seed(QDateTime::currentMSecsSinceEpoch() & 0xffffffff);
        seeded = true;
    }
    static boost::uuids::basic_random_generator<boost::mt19937> gen(&ran);

    tag = gen();
}
コード例 #2
0
ファイル: inference_utils.cpp プロジェクト: jotaraul/upgmpp
void UPGMpp::getRandomAssignation(CGraph &graph,
                                  map<size_t,size_t> &assignation,
                                  TInferenceOptions &options )
{
    static boost::mt19937 rng1;
    static bool firstExecution = true;

    if ( firstExecution )
    {
        rng1.seed(std::time(0));
        firstExecution = false;
    }

    vector<CNodePtr> &nodes = graph.getNodes();

    for ( size_t node = 0; node < nodes.size(); node++ )
    {
        // TODO: Check if a node has a fixed value and consider it

        size_t N_classes = nodes[node]->getType()->getNumberOfClasses();

        boost::uniform_int<> generator(0,N_classes-1);
        int state = generator(rng1);

        assignation[nodes[node]->getID()] = state;
    }

    /*map<size_t,size_t>::iterator it;
    for ( it = assignation.begin(); it != assignation.end(); it++ )
        cout << "[" << it->first << "] " << it->second << endl;*/
}
コード例 #3
0
ファイル: Utils.cpp プロジェクト: rodschulz/descriptor_lib
std::vector<T1> generateRandomSet(const unsigned int size_,
								  const T1 min_,
								  const T1 max_,
								  const bool allowRepetition_)
{
	generator.seed(std::rand());

#if BOOST_MINOR_VERSION <= 46
	NumberType range(min_, max_);
	boost::variate_generator<Generator&, NumberType> dist(generator, range);
#else
	Generator dist(min_, max_);
#endif

	std::vector<T1> numbers;
	numbers.reserve(size_);

	std::map<T1, bool> used;
	while (numbers.size() < size_)
	{
#if BOOST_MINOR_VERSION <= 46
		T1 number = dist();
#else
		T1 number = dist(generator);
#endif

		if (allowRepetition_ || used.find(number) == used.end())
		{
			used[number] = true;
			numbers.push_back(number);
		}
	}

	return numbers;
}
コード例 #4
0
	void readSeed(boost::program_options::variables_map& variableMap, boost::mt19937& randomSource)
	{
		if(variableMap.count("seed") > 0)
		{
			randomSource.seed(variableMap["seed"].as<int>());
		}
	}
コード例 #5
0
	void setUp() {
		randomGen.seed(time(NULL));
		eventLoop = new DummyEventLoop();
		timerFactory = new DummyTimerFactory();
		connection = boost::make_shared<MockeryConnection>(failingPorts, true, eventLoop);
		//connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1));
		//stream1 = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg")));
//		connection->onDataRead.connect(boost::bind(&SOCKS5BytestreamClientSessionTest::handleDataRead, this, _1));
	}
コード例 #6
0
	void setUp() {
		crypto = boost::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create());
		destination = "092a44d859d19c9eed676b551ee80025903351c2";
		randomGen.seed(static_cast<unsigned int>(time(NULL)));
		eventLoop = new DummyEventLoop();
		timerFactory = new DummyTimerFactory();
		connection = boost::make_shared<MockeryConnection>(failingPorts, true, eventLoop);
		//connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1));
		//stream1 = boost::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg")));
//		connection->onDataRead.connect(boost::bind(&SOCKS5BytestreamClientSessionTest::handleDataRead, this, _1));
	}
コード例 #7
0
ファイル: UUIDGenerator.cpp プロジェクト: ArenaCloud/kms-core
  void init ()
  {
    std::chrono::high_resolution_clock::time_point now =
      std::chrono::high_resolution_clock::now();

    std::chrono::nanoseconds time =
      std::chrono::duration_cast<std::chrono::nanoseconds>
      (now.time_since_epoch () );

    ran.seed (time.count() );

    pid = getpid();
  }
コード例 #8
0
ファイル: Utils.cpp プロジェクト: rodschulz/descriptor_lib
int Utils::getRandomNumber(const int min_,
						   const int max_)
{
	generator.seed(std::time(0));

#if BOOST_MINOR_VERSION <= 46
	boost::uniform_int<> range(min_, max_);
	boost::variate_generator<boost::mt19937&, boost::uniform_int<> > dist(generator, range);
	return dist();
#else
	boost::random::uniform_int_distribution<> dist(min_, max_);
	return dist(generator);
#endif
}
コード例 #9
0
ファイル: ZlibTest.cpp プロジェクト: alexandremattje/fbthrift
void parse_args(int argc, char* argv[]) {
  uint32_t seed = 0;
  bool has_seed = false;

  struct option long_opts[] = {
    { "help", false, nullptr, 'h' },
    { "seed", true, nullptr, 's' },
    { nullptr, 0, nullptr, 0 }
  };

  while (true) {
    optopt = 1;
    int optchar = getopt_long(argc, argv, "hs:", long_opts, nullptr);
    if (optchar == -1) {
      break;
    }

    switch (optchar) {
      case 's': {
        char *endptr;
        seed = strtol(optarg, &endptr, 0);
        if (endptr == optarg || *endptr != '\0') {
          fprintf(stderr, "invalid seed value \"%s\": must be a positive "
                  "integer\n", optarg);
          exit(1);
        }
        has_seed = true;
        break;
      }
      case 'h':
        print_usage(stdout, argv[0]);
        exit(0);
      case '?':
        exit(1);
      default:
        // Only happens if someone adds another option to the optarg string,
        // but doesn't update the switch statement to handle it.
        fprintf(stderr, "unknown option \"-%c\"\n", optchar);
        exit(1);
    }
  }

  if (!has_seed) {
    seed = time(nullptr);
  }

  printf("seed: %" PRIu32 "\n", seed);
  rng.seed(seed);
}
コード例 #10
0
ファイル: ZlibTest.cpp プロジェクト: NOMORECOFFEE/thrift
boost::unit_test::test_suite* init_unit_test_suite(int argc, char* argv[]) {
  THRIFT_UNUSED_VARIABLE(argc);
  THRIFT_UNUSED_VARIABLE(argv);
  uint32_t seed = static_cast<uint32_t>(time(NULL));
  printf("seed: %" PRIu32 "\n", seed);
  rng.seed(seed);

  boost::unit_test::test_suite* suite = &boost::unit_test::framework::master_test_suite();
  suite->p_name.value = "ZlibTest";

  uint32_t buf_len = 1024 * 32;
  add_tests(suite, gen_uniform_buffer(buf_len, 'a'), buf_len, "uniform");
  add_tests(suite, gen_compressible_buffer(buf_len), buf_len, "compressible");
  add_tests(suite, gen_random_buffer(buf_len), buf_len, "random");

  suite->add(BOOST_TEST_CASE(test_no_write));

  return NULL;
}
コード例 #11
0
ファイル: ZlibTest.cpp プロジェクト: DanielYWoo/thrift
bool init_unit_test_suite() {
  uint32_t seed = static_cast<uint32_t>(time(NULL));
#ifdef HAVE_INTTYPES_H
  printf("seed: %" PRIu32 "\n", seed);
#endif
  rng.seed(seed);

  boost::unit_test::test_suite* suite = &boost::unit_test::framework::master_test_suite();
  suite->p_name.value = "ZlibTest";

  uint32_t buf_len = 1024 * 32;
  add_tests(suite, gen_uniform_buffer(buf_len, 'a'), buf_len, "uniform");
  add_tests(suite, gen_compressible_buffer(buf_len), buf_len, "compressible");
  add_tests(suite, gen_random_buffer(buf_len), buf_len, "random");

  suite->add(BOOST_TEST_CASE(test_no_write));

  return true;
}
コード例 #12
0
ファイル: http_client.cpp プロジェクト: dot-Sean/Helix
float normalvariate(float mean, float sigma)
{
    static bool seeded = false;

    if (!seeded)
    {
        // seed generator with #seconds since 1970
        rng.seed(static_cast<unsigned> (std::time(0)));
        seeded = true;
    }

    // select desired probability distribution
    boost::normal_distribution<float> norm_dist(mean, sigma);

    // bind random number generator to distribution, forming a function
    boost::variate_generator<boost::mt19937&, boost::normal_distribution<float> >  normal_sampler(rng, norm_dist);

    // sample from the distribution
    return normal_sampler();
}
コード例 #13
0
ファイル: astar_maze.cpp プロジェクト: boostorg/graph
int main (int argc, char const *argv[]) {
  // The default maze size is 20x10.  A different size may be specified on
  // the command line.
  std::size_t x = 20;
  std::size_t y = 10;

  if (argc == 3) {
    x = boost::lexical_cast<std::size_t>(argv[1]);
    y = boost::lexical_cast<std::size_t>(argv[2]);
  }

  random_generator.seed(std::time(0));
  maze m(x, y);
  random_maze(m);
  if (m.solve())
    std::cout << "Solved the maze." << std::endl;
  else
    std::cout << "The maze is not solvable." << std::endl;
  std::cout << m << std::endl;
  return 0;
}
コード例 #14
0
ファイル: main.cpp プロジェクト: CCJY/coliru
int main() {
    rnd.seed(42);
    vertex_iterator vi,vi_end;
    Graph m_graph;

    auto start = chrono::high_resolution_clock::now();
    generate_random_graph(m_graph, 1000/*00*/, 500/*00*/, rnd); // reduced load for Coliru

    std::cout << "Generated " << num_vertices(m_graph) << " vertices and " << num_edges(m_graph) << " edges in "
        << chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start).count() << "ms\n"
        << "The graph has a cycle? " << std::boolalpha << has_cycle(m_graph) << "\n"
        << "starting selective removal...\n";

    start = chrono::high_resolution_clock::now();
    size_t count = 0;
    for (boost::tie(vi, vi_end) = boost::vertices(m_graph); vi!=vi_end;)
    {
        if (m_graph[*vi].guid.part1 == 0) {
            count++;
            clear_vertex(*vi, m_graph);
            //std::cout << "." << std::flush;
#if defined(STABLE_IT)
            auto toremove = vi++;
            boost::remove_vertex(*toremove,m_graph);
#else
            boost::remove_vertex(*vi,m_graph);
            boost::tie(vi, vi_end) = boost::vertices(m_graph);
#endif
        } else 
            ++vi;
    }

    std::cout << "Done in " << chrono::duration_cast<chrono::milliseconds>(
            chrono::high_resolution_clock::now() - start).count() << "ms\n";

    std::cout << "After: " << num_vertices(m_graph) << " vertices and " << num_edges(m_graph) << " edges\n";
}
コード例 #15
0
ファイル: mc_2d_voter.cpp プロジェクト: genneth/coarsen
int main(int argc, char ** argv)
{
	using namespace std;
	using namespace boost;

	if(argc <= 3) {
		cout << "usage: " << argv[0] << " <grid size> <time> <runs>" << endl;
		return -1;
	}

	int system_random = open("/dev/random", O_RDONLY);
	uint32_t seed;
	read(system_random, &seed, 4);
	close(system_random);

	rng.seed(seed);

	for(int count = 0; count < atoi(argv[3]);) {
		grid_lattice grid(atoi(argv[1]));
		while(true) {
			double dt = grid.next_event();
			grid.time += dt;
			if(grid.time > atof(argv[2])) break;
			grid.flip();
			if(grid.empty()) grid.restart();
		}

		if(!grid.empty()) {
			cout << grid.size() << endl;
//			cout << grid << endl;
			count++;
		}
	}

	return 0;
}
コード例 #16
0
void RandBipartiteGraph::GenerateGraph()
{
    // make n left-vertices
    for(unsigned int i = 0; i < n; i++){
        AddVariable(i);
    }

    vector<Vertex*> availableVertexList;
    availableVertexList.reserve(n);
    gen.seed(time(NULL));

    if (c%d != 0){
    // make c/d n right-vertices
        for(unsigned int i = 0; i < GetRightVerticesNumber(); i++){
            availableVertexList.push_back(static_cast<Vertex*>(AddConstraint(i)));
        }
    }

    for (unsigned int i = 0; i < n; i++){
        for(unsigned int j = 0; j < c; j++){
        	AddEdge(static_cast<Vertex*>(variables[i]), GetRandRightVertex(availableVertexList));
        }
    }
}
コード例 #17
0
ファイル: cogapsM.cpp プロジェクト: ejfertig/CoGAPS
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
//int main(int ac, char* av[]){

  // global objects for the program:
  /*Cogaps_options_class Cogaps_options(ac, av);
  try {
    // Cogaps_options_class Cogaps_options(ac, av); // WS -- change from Sasha's
    if (Cogaps_options.to_help){
      Cogaps_options.help(cout);
      return 0;
    }
    //cout << Cogaps_options; 
  } 
  catch( const exception & e) {
    cerr <<e.what()<<endl;
    return 1;
  }
*/
  // ===========================================================================
  // Initialization of the random number generator.
  // Different seeding methods:
  // --- fixed seed 
  //std::vector<unsigned long> ve(2);
  //ve[0]=198782;ve[1]=89082;
  //boost::random::seed_seq seq(ve);
  //rng.seed(seq);
  // --- seeded with time
  rng.seed(static_cast<boost::uint32_t>(std::time(0)));
  //---------------------

  // ===========================================================================
  // Part 1) Initialization: 
  // In this section, we read in the system parameters from the paremter file
  // parameter.txt, and matrices D and S from datafile.txt. 
  // Then we initialize A and P in both their atomic domains and 
  // matrix forms.
  // ===========================================================================
	
	//Matlab pointers for inputs
    mxArray* DArrayElems;
	mxArray* SArrayElems;
	mxArray* InputColsPtr;
	mxArray* InputRowsPtr;

	//Matlab pointers for config 
	mxArray* nFactorPtr;
	mxArray* simulationIDPtr;
	mxArray* nEquilPtr;
	mxArray* nSamplePtr;
	mxArray* QAtomicPtr;
	mxArray* alphaAPtr;
	mxArray* nIterAPtr;
	mxArray* nMaxAPtr;
	mxArray* maxGibbsAPtr;
	mxArray* lambdaAScalePtr;
	mxArray* alphaPPtr;
	mxArray* nIterPPtr;
	mxArray* nMaxPPtr;
	mxArray* maxGibbsPPtr;
	mxArray* lambdaPScalePtr;
	
	//Transferring inputs from mex gateway to pointers
	DArrayElems = mxGetCell(prhs[0], 0);
	SArrayElems = mxGetCell(prhs[0], 1);
	InputColsPtr = mxGetCell(prhs[0], 2);
	InputRowsPtr = mxGetCell(prhs[0], 3);
	nFactorPtr = mxGetCell(prhs[0], 4);
	simulationIDPtr = mxGetCell(prhs[0], 5);
	nEquilPtr = mxGetCell(prhs[0], 6);
	nSamplePtr = mxGetCell(prhs[0], 7);
	QAtomicPtr = mxGetCell(prhs[0], 8);
	alphaAPtr = mxGetCell(prhs[0], 9);
	nIterAPtr = mxGetCell(prhs[0], 10);
	nMaxAPtr = mxGetCell(prhs[0], 11);
	maxGibbsAPtr = mxGetCell(prhs[0], 12);
	lambdaAScalePtr = mxGetCell(prhs[0], 13);
	alphaPPtr = mxGetCell(prhs[0], 14);
	nIterPPtr = mxGetCell(prhs[0], 15);
	nMaxPPtr = mxGetCell(prhs[0], 16);
	maxGibbsPPtr = mxGetCell(prhs[0], 17);
	lambdaPScalePtr = mxGetCell(prhs[0], 18);
	
	
	//creating native C style data types
	double* DArray;
	double* SArray;
	double* numInputRows;
	double* numInputCols;
	
	//Establish the C types for the Config Information
	double* nFactorC = mxGetPr(nFactorPtr);
	
	int ptrLength; 
	char* simulationIDC;
	ptrLength = mxGetNumberOfElements(simulationIDPtr) + 1;
	simulationIDC = (char *)(mxCalloc(ptrLength, sizeof(char)));
	mxGetString(simulationIDPtr, simulationIDC, ptrLength);
	
	double* nEquilC = mxGetPr(nEquilPtr);
	double* nSampleC = mxGetPr(nSamplePtr);
	double* QAtomicC = mxGetPr(QAtomicPtr);
	double* alphaAC = mxGetPr(alphaAPtr);
	double* nIterAC = mxGetPr(nIterAPtr);
	double* nMaxAC = mxGetPr(nMaxAPtr);
	double* maxGibbsAC = mxGetPr(maxGibbsAPtr);
	double* lambdaAScaleC = mxGetPr(lambdaAScalePtr);
	double*	alphaPC = mxGetPr(alphaPPtr);
	double*	nIterPC = mxGetPr(nIterPPtr);
	double* nMaxPC = mxGetPr(nMaxPPtr);
	double* maxGibbsPC = mxGetPr(maxGibbsPPtr);
	double* lambdaPScaleC = mxGetPr(lambdaPScalePtr);
	
	int nIRows;
	int nICols;
	
	
	
	//converting from pointer to matlab type then to C array
	DArray = mxGetPr(DArrayElems);
	SArray = mxGetPr(SArrayElems);
	numInputCols = mxGetPr(InputRowsPtr);
	numInputRows = mxGetPr(InputColsPtr);
	
	//removing need for arrays for dimensions
	nIRows = numInputRows[0];
	nICols = numInputCols[0];
	
	//Putting C style arrays into C++ vectors to pass to the Gibbs Sampler
	vector< vector<double> > DVector(nIRows, vector<double>(nICols));
	vector< vector<double> > SVector(nIRows, vector<double>(nICols));
	
	for(int i = 0; i < nIRows; i++)
	{
		for(int j = 0; j < nICols; j++)
		{
			DVector[i][j] = DArray[i + (j*nIRows)];
		}
	}
	
	for(int i = 0; i < nIRows; i++)
	{
		for(int j = 0; j < nICols; j++)
		{
			SVector[i][j] = SArray[i + (j*nIRows)];
		}
	}
	
	/*Testing output of matrices
	cout << endl;
	for(int i = 0; i < nIRows; i++)
	{
		for(int j = 0; j < nICols; j++)
		{
			cout << DVector[i][j] << " ";
		}
		cout << endl;
	}
	
	cout << endl;
	for(int i = 0; i < nIRows; i++)
	{
		for(int j = 0; j < nICols; j++)
		{
			cout << SVector[i][j] << " ";
		}
		cout << endl;
	}
	*/
	
  // Parameters or data to be read in:
  unsigned long nEquil = nEquilC[0]; //Cogaps_options.nEquil;    // # outer loop iterations 
                                                   // for equilibration
  unsigned long nSample = nSampleC[0];//Cogaps_options.nSample;  // # outer loop iterations 
                                                   // for sampling
  unsigned int nFactor = nFactorC[0]; //Cogaps_options.nFactor;   // # patterns
  double alphaA = alphaAC[0]; //Cogaps_options.alphaA;
  double alphaP = alphaPC[0]; //Cogaps_options.alphaP;
  double nMaxA = nMaxAC[0];//Cogaps_options.nMaxA;             // max. number of atoms in A
  double nMaxP = nMaxPC[0];//Cogaps_options.nMaxP;             // number of atomic bins for P
  //string datafile = "Data2.txt";//Cogaps_options.datafile;        // File for D
  //string variancefile = "Noise2.txt";//Cogaps_options.variancefile; // File for S
  string simulation_id = simulationIDC;//Cogaps_options.simulation_id; // simulation id
  unsigned long nIterA = nIterAC[0];//Cogaps_options.nIterA;    // initial # of inner-loop iterations for A 
  unsigned long nIterP = nIterPC[0];//Cogaps_options.nIterP;    // initial # of inner-loop iterations for P 
  double max_gibbsmass_paraA = maxGibbsAC[0];//Cogaps_options.max_gibbsmass_paraA; 
                           // maximum gibbs mass parameter for A 
  double max_gibbsmass_paraP = maxGibbsPC[0];//Cogaps_options.max_gibbsmass_paraP; 
                           // maximum gibbs mass parameter for P 
  double lambdaA_scale_factor = lambdaAScaleC[0];//Cogaps_options.lambdaA_scale_factor;
                           // scale factor for lambdaA
  double lambdaP_scale_factor = lambdaPScaleC[0];//Cogaps_options.lambdaP_scale_factor;
                           // scale factor for lambdaP
  bool Q_output_atomic = QAtomicC[0];//Cogaps_options.Q_output_atomic;
                           // whether to output the atomic space info

  // Parameters or structures to be calculated or constructed:
  unsigned int nRow;       // number of items in observation (= # of genes)
  unsigned int nCol;       // number of observation (= # of arrays)
  unsigned int nBinsA;     // number of atomic bins for A
  unsigned int nBinsP;     // number of atomic bins for P
  double lambdaA;
  double lambdaP;
  //unsigned long nIterA;    // number of inner loop iterations for A
  //unsigned long nIterP;    // number of inner loop iterations for P  
  //atomic At, Pt;           // atomic space for A and P respectively
  unsigned long atomicSize; // number of atomic points

  char label_A = 'A';  // label for matrix A
  char label_P = 'P';  // label for matrix P
  char label_D = 'D';  // label for matrix D
  char label_S = 'S';// label for matrix S

  // Output parameters and computing info to files:
  /* Commented out for Matlab and R Versions
  char outputFilename[80];
  strcpy(outputFilename,simulation_id.c_str());
  strcat(outputFilename,"_computing_info.txt");
  
 
  ofstream outputFile;
  outputFile.open(outputFilename,ios::out);  // start by deleting previous content and 
                                             // rewriting the file
  outputFile << "Common parameters and info:" << endl;
  outputFile << "input data file: " << datafile << endl;
  outputFile << "input variance file: " << variancefile << endl;
  outputFile << "simulation id: " << simulation_id << endl;
  outputFile << "nFactor = " << nFactor << endl;
  outputFile << "nEquil = " << nEquil << endl;
  outputFile << "nSample = " << nSample << endl;
  outputFile << "Q_output_atomic (bool) = " << Q_output_atomic << endl << endl;

  outputFile << "Parameters for A:" << endl;
  outputFile << "alphaA = " << alphaA << endl;
  outputFile << "nMaxA = " << nMaxA << endl;
  outputFile << "nIterA = " << nIterA << endl;
  outputFile << "max_gibbsmass_paraA = " << max_gibbsmass_paraA << endl;
  outputFile << "lambdaA_scale_factor = " << lambdaA_scale_factor << endl << endl;

  outputFile << "Parameters for P:" << endl;
  outputFile << "alphaP = " << alphaP << endl;
  outputFile << "nMaxP = " << nMaxP << endl;
  outputFile << "nIterP = " << nIterP << endl;
  outputFile << "max_gibbsmass_paraP = " << max_gibbsmass_paraP << endl;
  outputFile << "lambdaP_scale_factor = " << lambdaP_scale_factor << endl << endl;

  outputFile.close();
  */



  // ---------------------------------------------------------------------------
  // Initialize the GibbsSampler.

  /*Regular Version
  GibbsSampler GibbsSamp(nEquil,nSample,nFactor,   // construct GibbsSampler and 
                         alphaA,alphaP,nMaxA,nMaxP,// Read in D and S matrices
                         nIterA,nIterP,
			 max_gibbsmass_paraA, max_gibbsmass_paraP, 
			 lambdaA_scale_factor, lambdaP_scale_factor,
                         atomicSize,
                         label_A,label_P,label_D,label_S,
			 datafile,variancefile,simulation_id);
	*/
	
	//R and Matlab Version
	GibbsSampler GibbsSamp(nEquil,nSample,nFactor,   // construct GibbsSampler and 
                         alphaA,alphaP,nMaxA,nMaxP,// Read in D and S matrices
                         nIterA,nIterP,
			 max_gibbsmass_paraA, max_gibbsmass_paraP, 
			 lambdaA_scale_factor, lambdaP_scale_factor,
                         atomicSize,
                         label_A,label_P,label_D,label_S,
			 DVector,SVector,simulation_id);

  // ---------------------------------------------------------------------------
  // Based on the information of D, construct and initialize for A and P both 
  // the matrices and atomic spaces.

  GibbsSamp.init_AMatrix_and_PMatrix(); // initialize A and P matrices
  GibbsSamp.init_AAtomicdomain_and_PAtomicdomain(); // intialize atomic spaces
                                                    // A and P
  GibbsSamp.init_sysChi2(); // initialize the system chi2 value

  // ===========================================================================
  // Part 2) Equilibration:
  // In this section, we let the system eqilibrate with nEquil outer loop 
  // iterations. Within each outer loop iteration, A is iterated nIterA times 
  // and P is iterated nIterP times. After equilibration, we update nIterA and 
  // nIterP according to the expected number of atoms in the atomic spaces 
  // of A and P respectively.
  // ===========================================================================
  
      // --------- temp for initializing output to chi2.txt
	  /*
      char outputchi2_Filename[80];
      strcpy(outputchi2_Filename,simulation_id.c_str());
      strcat(outputchi2_Filename,"_chi2.txt");
      ofstream outputchi2_File;
      outputchi2_File.open(outputchi2_Filename,ios::out);
      outputchi2_File << "chi2" << endl;
      outputchi2_File.close();
	  */
      // --------------
      


  double chi2;
  //Matlab control variables 
  double tempChiSq;
  double tempAtomA;
  double tempAtomP;
	int outCount = 0;
	int numOutputs = 100; 
	int totalChiSize = nSample + nEquil;
	
	//Establishing Matlab containers for atoms and chisquare
	double* nAEquil;
	mxArray* nAEMx;
	nAEMx = mxCreateDoubleMatrix(1, nEquil, mxREAL);
	nAEquil = mxGetPr(nAEMx);
	
	double* nASamp;
	mxArray* nASMx;
	nASMx = mxCreateDoubleMatrix(1, nSample, mxREAL);
	nASamp = mxGetPr(nASMx);
	
	double* nPEquil;
	mxArray* nPEMx;
	nPEMx = mxCreateDoubleMatrix(1, nEquil, mxREAL);
	nPEquil = mxGetPr(nPEMx);
	
	double* nPSamp;
	mxArray* nPSMx;
	nPSMx = mxCreateDoubleMatrix(1, nSample, mxREAL);
	nPSamp = mxGetPr(nPSMx);
	
	double* chiVect;
	mxArray* chiMx;
	chiMx = mxCreateDoubleMatrix(1, totalChiSize, mxREAL);
	chiVect = mxGetPr(chiMx);
	

  for (unsigned long ext_iter=1; ext_iter <= nEquil; ++ext_iter){
    GibbsSamp.set_iter(ext_iter);
    GibbsSamp.set_AnnealingTemperature();


    for (unsigned long iterA=1; iterA <= nIterA; ++iterA){
      GibbsSamp.update('A');
	  GibbsSamp.check_atomic_matrix_consistency('A');
      //GibbsSamp.check_atomic_matrix_consistency('A');
      //GibbsSamp.detail_check(outputchi2_Filename);
    }
    

    for (unsigned long iterP=1; iterP <= nIterP; ++iterP){
      GibbsSamp.update('P');
	  GibbsSamp.check_atomic_matrix_consistency('P');

      //GibbsSamp.check_atomic_matrix_consistency('P');
      //GibbsSamp.detail_check(outputchi2_Filename);
    }
	tempChiSq = GibbsSamp.get_sysChi2();
	chiVect[(ext_iter)-1] = tempChiSq;

	tempAtomA = GibbsSamp.getTotNumAtoms('A');
	tempAtomP = GibbsSamp.getTotNumAtoms('P');
	nAEquil[outCount] = tempAtomA;
	nPEquil[outCount] = tempAtomP;
	outCount++;
    // ----------- output computing info ---------
    if ( ext_iter % numOutputs == 0){
      //chi2 = 2.*GibbsSamp.cal_logLikelihood();
      
      cout << "Equil: " << ext_iter << " of " << nEquil << 
              " ,nA: " << tempAtomA <<
	      " ,nP: " << tempAtomP << 
	// " ,chi2 = " << chi2 <<
              " ,System Chi2 = " << tempChiSq << endl;
    }

    // -------------------------------------------
    // re-calculate nIterA and nIterP to the expected number of atoms 
    nIterA = (unsigned long) randgen('P',max((double) GibbsSamp.getTotNumAtoms('A'),10.));
    nIterP = (unsigned long) randgen('P',max((double) GibbsSamp.getTotNumAtoms('P'),10.));
    //nIterA = (unsigned long) randgen('P',(double) GibbsSamp.getTotNumAtoms('A')+10.);
    //nIterP = (unsigned long) randgen('P',(double) GibbsSamp.getTotNumAtoms('P')+10.);
    // --------------------------------------------

  }  // end of for-block for equilibration
 


  // ===========================================================================
  // Part 3) Sampling:
  // After the system equilibriates in Part 2, we sample the systems with an 
  // outer loop of nSample iterations. Within each outer loop iteration, A is 
  // iterated nIterA times and P is iterated nIterP times. After sampling, 
  // we update nIterA and nIterP according to the expected number of atoms in 
  // the atomic spaces of A and P respectively.
  // ===========================================================================
  


  unsigned int statindx = 0;
  outCount = 0;
  for (unsigned long ext_iter=1; ext_iter <= nSample; ++ext_iter){
    for (unsigned long iterA=1; iterA <= nIterA; ++iterA){
      GibbsSamp.update('A');
      //GibbsSamp.check_atomic_matrix_consistency('A');
      //GibbsSamp.detail_check(outputchi2_Filename);
    }
    GibbsSamp.check_atomic_matrix_consistency('A');

    for (unsigned long iterP=1; iterP <= nIterP; ++iterP){ 
      GibbsSamp.update('P');
      //GibbsSamp.check_atomic_matrix_consistency('P');
      //GibbsSamp.detail_check(outputchi2_Filename);
    }
    GibbsSamp.check_atomic_matrix_consistency('P');

    if (Q_output_atomic == true){
       GibbsSamp.output_atomicdomain('A',ext_iter);
       GibbsSamp.output_atomicdomain('P',ext_iter);
    }

     statindx += 1;
     GibbsSamp.compute_statistics_prepare_matrices(statindx);
	 
	tempChiSq = GibbsSamp.get_sysChi2();
	
	chiVect[(nEquil + ext_iter)-1] = tempChiSq;
	
	tempAtomA = GibbsSamp.getTotNumAtoms('A');
	tempAtomP = GibbsSamp.getTotNumAtoms('P');
	nASamp[outCount] = tempAtomA;
	nPSamp[outCount] = tempAtomP;
	outCount++;
    // ----------- output computing info ---------
    if ( ext_iter % numOutputs == 0){
  
      // chi2 = 2.*GibbsSamp.cal_logLikelihood();
      //GibbsSamp.output_atomicdomain('A',(unsigned long) statindx);
      //GibbsSamp.output_atomicdomain('P',(unsigned long) statindx);
		
      cout << "Samp: " << ext_iter << " of " << nSample << 
              " ,nA: " << tempAtomA <<
	      " ,nP: " << tempAtomP << 
	// " ,chi2 = " << chi2 <<
              " , System Chi2 = " << tempChiSq << endl;
		
      if (ext_iter == nSample){
         chi2 = 2.*GibbsSamp.cal_logLikelihood();
	 cout << " *** Check value of final chi2: " << chi2 << " **** " << endl; 
      }



    }

    // -------------------------------------------
    // re-calculate nIterA and nIterP to the expected number of atoms 
    nIterA = (unsigned long) randgen('P',max((double) GibbsSamp.getTotNumAtoms('A'),10.));
    nIterP = (unsigned long) randgen('P',max((double) GibbsSamp.getTotNumAtoms('P'),10.));
    //nIterA = (unsigned long) randgen('P',(double) GibbsSamp.getTotNumAtoms('A')+10.);
    //nIterP = (unsigned long) randgen('P',(double) GibbsSamp.getTotNumAtoms('P')+10.);
    // --------------------------------------------

  }  // end of for-block for Sampling

 

  // ===========================================================================
  // Part 4) Calculate statistics:
  // In this final section, we calculate all statistics pertaining to the final
  // sample and check the results.
  // ===========================================================================

  char outputAmean_Filename[80];
  strcpy(outputAmean_Filename,simulation_id.c_str());
  strcat(outputAmean_Filename,"_Amean.txt");

  char outputAsd_Filename[80];
  strcpy(outputAsd_Filename,simulation_id.c_str());
  strcat(outputAsd_Filename,"_Asd.txt");

  char outputPmean_Filename[80];
  strcpy(outputPmean_Filename,simulation_id.c_str());
  strcat(outputPmean_Filename,"_Pmean.txt");

  char outputPsd_Filename[80];
  strcpy(outputPsd_Filename,simulation_id.c_str());
  strcat(outputPsd_Filename,"_Psd.txt");

  char outputAPmean_Filename[80];
  strcpy(outputAPmean_Filename,simulation_id.c_str());
  strcat(outputAPmean_Filename,"_APmean.txt");



 /* GibbsSamp.compute_statistics(outputFilename,
                               outputAmean_Filename,outputAsd_Filename,
			       outputPmean_Filename,outputPsd_Filename,
			       outputAPmean_Filename,
                               statindx);          // compute statistics like mean and s.d.n */
							   
	vector<vector <double> > AMeanVector;
	vector<vector <double> > AStdVector;
	vector<vector <double> > PMeanVector;
	vector<vector <double> > PStdVector;
	
	GibbsSamp.compute_statistics(statindx,
							   AMeanVector, AStdVector, PMeanVector, PStdVector);   
	
	/*
	cout << endl;
	for(int i = 0; i < AMeanVector.size(); i++)
	{
		for(int j = 0; j < AMeanVector[0].size(); j++)
		{
			cout << AMeanVector[i][j] << " "; 
		}
		cout << endl;
	}
	*/
	
	/*double *x,*y;
	size_t mrows,ncols;
	mrows = mxGetM(prhs[0]);
	ncols = mxGetN(prhs[0]);
	plhs[0] = mxCreateDoubleMatrix((mwSize)mrows, (mwSize)ncols, mxREAL);
	x = mxGetPr(prhs[0]);
	y = mxGetPr(plhs[0]);*/
	
	//Get Dims of Matrices for matlab
	int nrowA, ncolA;
	int nrowP, ncolP;
	ncolA = AMeanVector.size();
	nrowA = AMeanVector[0].size();
	ncolP = PMeanVector.size();
	nrowP = PMeanVector[0].size();
	
	//Declare Matrices for matlab
	double* AMeanMatArray;
	double* AStdMatArray;
	double* PMeanMatArray;
	double* PStdMatArray;
	
	//Convertible Matlab datatypes
	mxArray* AMeanMx;
	mxArray* AStdMx;
	mxArray* PMeanMx;
	mxArray* PStdMx;
	
	//Allocate memory for the Matlab Matrices and establish their data types
	AMeanMx = mxCreateDoubleMatrix(ncolA, nrowA, mxREAL);
	AStdMx = mxCreateDoubleMatrix(ncolA, nrowA, mxREAL);
	PMeanMx = mxCreateDoubleMatrix(ncolP, nrowP, mxREAL);
	PStdMx = mxCreateDoubleMatrix(ncolP, nrowP, mxREAL);
	
	
	//Steps to Create the Cell Array to pass back the data matrices 
	mxArray* TempArry;
	const int* dims;
	TempArry = mxCreateDoubleMatrix(9, 9, mxREAL); //TODO, currently creating the dimensions of a cell Matrix by creating a temp matrix due to lack of understanding of mex datatypes, fix!
	dims = mxGetDimensions(TempArry);
	plhs[0] = mxCreateCellArray(1, dims);
	
	

	 //Fill the matrices individually 
	AMeanMatArray = mxGetPr(AMeanMx);
	double tempVectValue;
	for(int i = 0; i < ncolA; i++)
	{
		for(int j = 0; j < nrowA; j++)
		{
			tempVectValue = AMeanVector[i][j];
			AMeanMatArray[i + (j*ncolA)] = tempVectValue;
		}
	}
	
	AStdMatArray = mxGetPr(AStdMx);
	for(int i = 0; i < ncolA; i++)
	{
		for(int j = 0; j < nrowA; j++)
		{
			tempVectValue = AStdVector[i][j];
			AStdMatArray[i + (j*ncolA)] = tempVectValue;
		}
	}
	
	PMeanMatArray = mxGetPr(PMeanMx);
	for(int i = 0; i < ncolP; i++)
	{
		for(int j = 0; j < nrowP; j++)
		{
			tempVectValue = PMeanVector[i][j];
			PMeanMatArray[i + (j*ncolP)] = tempVectValue;
		}
	}
	
	PStdMatArray = mxGetPr(PStdMx);
	for(int i = 0; i < ncolP; i++)
	{
		for(int j = 0; j < nrowP; j++)
		{
			tempVectValue = PStdVector[i][j];
			PStdMatArray[i + (j*ncolP)] = tempVectValue;
		}
	}
	
	mxSetCell(plhs[0], 0, AMeanMx);
	mxSetCell(plhs[0], 1, AStdMx);
	mxSetCell(plhs[0], 2, PMeanMx);
	mxSetCell(plhs[0], 3, PStdMx);
	mxSetCell(plhs[0], 4, nAEMx);
	mxSetCell(plhs[0], 5, nASMx);
	mxSetCell(plhs[0], 6, nPEMx);
	mxSetCell(plhs[0], 7, nPSMx);
	mxSetCell(plhs[0], 8, chiMx);
	
}
コード例 #18
0
ファイル: test.cpp プロジェクト: atofigh/edmonds-alg
int
main(int argc, char *argv[])
{
    // Parse and read the command line arguments.
    if (argc != 5)
    {
        cerr << "Usage: " << PNAME
             << " <min-weight> <max-weight> <#vertices> <#tests>\n";
        exit(1);
    }

    long int min_weight = strtol(argv[1], 0, 0);
    long int max_weight = strtol(argv[2], 0, 0);
    long int n_vertices = strtol(argv[3], 0, 0);
    long int n_tests = strtol(argv[4], 0, 0);

    if (errno)
    {
        cerr << "Bad arguments\n";
        exit(1);
    }

    // Check consistency of command line arguments.
    if (n_tests < 0)
    {
        cerr << "the number of tests must be a positive integer\n";
        exit(1);
    }
    
    if (n_vertices > numeric_limits<unsigned>::digits)
    {
        cerr << "Too many vertices\n"
             << "Maximum n.o. vertices is "
             << numeric_limits<unsigned>::digits << "\n";
        exit(1);
    }

    if (n_vertices < 2)
    {
        cerr << "Too few vertices\n"
             << "must be at least two\n";
        exit(1);
    }

    if (min_weight > max_weight)
    {
        cerr << "min weight must be greater than max weight\n";
        exit(1);
    }

    if (abs(max_weight) >= numeric_limits<int>::max() / n_vertices ||
        abs(min_weight) >= numeric_limits<int>::max() / n_vertices)
    {
        cerr << "weights too large\n";
        exit(1);
    }

    // Initialize the random number generator.
    timeval tv;
    gettimeofday(&tv, 0);
    g_generator.seed(tv.tv_sec * 1000000 + tv.tv_usec);
    boost::uniform_int<int> uniform_int_dist(min_weight, max_weight);
    boost::variate_generator<mt19937, uniform_int<int> > rng_i(g_generator, uniform_int_dist);
    
    // Perform the tests.
    enum {MAX_SPAN_0, MAX_SPAN_1, MAX_SPAN_2,
          MAX_NOSPAN_0, MAX_NOSPAN_1, MAX_NOSPAN_2,
          MIN_SPAN_0, MIN_SPAN_1, MIN_SPAN_2,
          MIN_NOSPAN_0, MIN_NOSPAN_1, MIN_NOSPAN_2,
          N_CASES};
    string case_names[] = {
        "MAX_SPAN_0", "MAX_SPAN_1", "MAX_SPAN_2",
        "MAX_NOSPAN_0", "MAX_NOSPAN_1", "MAX_NOSPAN_2",
        "MIN_SPAN_0", "MIN_SPAN_1", "MIN_SPAN_2",
        "MIN_NOSPAN_0", "MIN_NOSPAN_1", "MIN_NOSPAN_2"
    };

    complete_graph      g(n_vertices);
    multi_array<int, 2> weights(extents[n_vertices][n_vertices]);
    vector<Vertex>      parent(n_vertices);
    Vertex              roots[] = {0, 1};

    vector<Edge>        branching;
    vector< vector< Edge > > all_branchings(N_CASES);
    vector<int>         ans(N_CASES);

    while (n_tests--)
    {
        // Clear all the branchings from previous iteration.
        BOOST_FOREACH (vector<Edge> &vec, all_branchings)
        {
            vec.clear();
        }

        // create new weights
        int *end = weights.origin() + n_vertices * n_vertices;
        for (int *ip = weights.origin(); ip != end; ++ip)
        {
            *ip = rng_i();
        }
        
        // run edmonds algorithm for a few cases. The cases will be
        // the cross product of the following properties:
        // optimum-is-maximum x attempt-to-span x num-specified-roots
        // where num-specified roots is either 0, 1, or 2. Also the
        // specified roots are either none, the vertex 0, or the
        // vertices 0 and 1.
        edmonds_optimum_branching<true, true, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 0, back_inserter(all_branchings[MAX_SPAN_0]));
        edmonds_optimum_branching<true, true, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 1, back_inserter(all_branchings[MAX_SPAN_1]));
        edmonds_optimum_branching<true, true, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 2, back_inserter(all_branchings[MAX_SPAN_2]));
        edmonds_optimum_branching<true, false, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 0, back_inserter(all_branchings[MAX_NOSPAN_0]));
        edmonds_optimum_branching<true, false, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 1, back_inserter(all_branchings[MAX_NOSPAN_1]));
        edmonds_optimum_branching<true, false, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 2, back_inserter(all_branchings[MAX_NOSPAN_2]));
        edmonds_optimum_branching<false, true, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 0, back_inserter(all_branchings[MIN_SPAN_0]));
        edmonds_optimum_branching<false, true, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 1, back_inserter(all_branchings[MIN_SPAN_1]));
        edmonds_optimum_branching<false, true, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 2, back_inserter(all_branchings[MIN_SPAN_2]));
        edmonds_optimum_branching<false, false, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 0, back_inserter(all_branchings[MIN_NOSPAN_0]));
        edmonds_optimum_branching<false, false, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 1, back_inserter(all_branchings[MIN_NOSPAN_1]));
        edmonds_optimum_branching<false, false, true>
            (g, identity_property_map(), weights.origin(),
             roots, roots + 2, back_inserter(all_branchings[MIN_NOSPAN_2]));

        for (int i = 0; i < N_CASES; ++i)
        {
            ans[i] = 0;
            BOOST_FOREACH (Edge e, all_branchings[i])
            {
                ans[i] += weights[source(e, g)][target(e, g)];
            }
        }

        // Exhaustively test all branchings and check if the answers
        // from edmonds's algorithm is optimal.
        int bad_case = -1;
        fill(parent.begin(), parent.end(), 0);
        do
        {
            if (is_cyclic(parent))
                continue;
            
            int weight = 0;
            for (int i = 0; i < n_vertices; ++i)
            {
                if (parent[i] == i)
                    continue;
                
                weight += weights[parent[i]][i];
            }

            int num_roots = 0;
            for (int i = 0; i < n_vertices; ++i)
            {
                num_roots += parent[i] == i ? 1 : 0;
            }

            bad_case = MAX_NOSPAN_0;
            if (weight > ans[bad_case])
                break;

            bad_case = MIN_NOSPAN_0;
            if (weight < ans[bad_case])
                break;

            bad_case = MAX_NOSPAN_1;
            if (parent[0] == 0 && weight > ans[bad_case])
                break;

            bad_case = MIN_NOSPAN_1;
            if (parent[0] == 0 && weight < ans[bad_case])
                break;

            bad_case = MAX_NOSPAN_2;
            if (parent[0] == 0 && parent[1] == 1 && weight > ans[bad_case])
                break;

            bad_case = MIN_NOSPAN_2;
            if (parent[0] == 0 && parent[1] == 1 && weight < ans[bad_case])
                break;

            bad_case = MAX_SPAN_0;
            if (num_roots == 1 && weight > ans[bad_case])
                break;

            bad_case = MIN_SPAN_0;
            if (num_roots == 1 && weight < ans[bad_case])
                break;

            bad_case = MAX_SPAN_1;
            if (num_roots == 1 && parent[0] == 0 && weight > ans[bad_case])
                break;

            bad_case = MIN_SPAN_1;
            if (num_roots == 1 && parent[0] == 0 && weight < ans[bad_case])
                break;

            bad_case = MAX_SPAN_2;
            if (num_roots == 1 && parent[0] == 0 && parent[1] == 1 &&
                weight > ans[bad_case])
                break;

            bad_case = MIN_SPAN_2;
            if (num_roots == 1 && parent[0] == 0 && parent[1] == 1 &&
                weight < ans[bad_case])
                break;

            bad_case = -1;
        } while (next_parent(parent));

        // If we broke out of the loop prematurely, then something was
        // wrong.
        if (bad_case > 0)
        {
            cout << "\ntest failed.\n";
            
            cout << "weights:\n";
            for (int i = 0; i < n_vertices; ++i)
            {
                for (int j = 0; j < n_vertices; ++j)
                {
                    cout << weights[i][j] << " ";
                }
                cout << "\n";
            }
            cout << "\n";
            
            int weight = 0;
            for (int i = 0; i < n_vertices; ++i)
            {
                if (parent[i] == i)
                    continue;
                
                weight += weights[parent[i]][i];
            }

            cout << "counter example (weight = " << weight << "):\n";
            for (int i = 0; i < n_vertices; ++i)
            {
                if (parent[i] == i)
                    continue;
                cout << "(" << parent[i] << ", " << i << ")\t";
            }
            cout << "\n";

            weight = 0;
            cout << "case: " << case_names[bad_case] << ":\n";
            BOOST_FOREACH (Edge e, all_branchings[bad_case])
            {
                cout << "(" << source(e, g) << ", " << target(e, g) << ")\t";
                weight += weights[source(e, g)][target(e, g)];
            }
            cout << "\n";
            cout << "weight:\t" << weight << "\n";

            exit(1);
        }
コード例 #19
0
ファイル: servers.hpp プロジェクト: ghoff/accessl
 servers_chooser()
 {
     boost::random_device dev;
     rng_.seed(dev());
 }
コード例 #20
0
ファイル: TransportTest.cpp プロジェクト: jihlee/thrift
void initrand(unsigned int seed) {
    rng.seed(seed);
}
コード例 #21
0
ファイル: example.cpp プロジェクト: caomw/upgmpp
int main (int argc, char* argv[])
{

    cout << endl;
    cout << "      MAP AND MARGINAL INFERENCE EXAMPLE";
    cout << endl << endl;

/*------------------------------------------------------------------------------
 *
 *                         PREPARE TRAINING DATA
 *
 *----------------------------------------------------------------------------*/

    //
    // Generate the types of nodes and edges
    //

    size_t N_classes_type_1        = 11;
    size_t N_nf   = 5;
    size_t N_ef   = 4;

    // OBJECTS

    CNodeTypePtr simpleNodeType1Ptr( new CNodeType(N_classes_type_1,
                                                   N_nf,
                                                   string("Objects") ) );

    CEdgeTypePtr simpleEdgeType1Ptr ( new CEdgeType(N_ef,
                                                    simpleNodeType1Ptr,
                                                    simpleNodeType1Ptr,
                                                    string("Edges between two objects")) );


    trainingDataset.addNodeType( simpleNodeType1Ptr );
    trainingDataset.addEdgeType( simpleEdgeType1Ptr );

    //
    // Create a set of training graphs
    //

    vector<CGraph>                      graphs;
    vector<std::map<size_t,size_t> >    groundTruths;

/*--------------------------------- Graph 1 ----------------------------------*/


    cout << "Graph 1" << endl;

    CGraph graph1;
    std::map<size_t,size_t> groundTruth1;

    Eigen::MatrixXd g1_nf(11,5);

    g1_nf << 1, 0.725256, 0.347833, 2.32114, 1,
             0, 0, 1.46145, 2.86637, 1,
             1, 0.513579, 0.398025, 1.85308, 1,
             0, 0.896507, 0.969337, 1.7035, 1,
             0, 0.748331, 0.585186, 1.47532, 1,
             1, 0.963636, 0.125714, 1, 1,
             1, 0.93444, 0.212592, 1.52702, 1,
             1, 1.05757, 0.236803, 3.22358, 1,
             0, 0.398408, 0.131399, 1, 1,
             0, 0.0300602, 0.129521, 2.03183, 1,
             1, 0.469344, 0.505431, 1.45506, 1;

    Eigen::MatrixXi g1_adj(11,11);

    g1_adj <<   0,  1,  1,  1,  1,  1,  0,  0,  1,  1,  0,
                1,  0,  1,  0,  0,  0,  0,  0,  1,  1,  0,
                1,  1,  0,  0,  0,  0,  0,  0,  0,  0,  0,
                1,  0,  0,  0,  1,  1,  1,  1,  1,  0,  1,
                1,  0,  0,  1,  0,  1,  1,  1,  1,  1,  1,
                1,  0,  0,  1,  1,  0,  1,  0,  0,  0,  0,
                0,  0,  0,  1,  1,  1,  0,  1,  1,  0,  1,
                0,  0,  0,  1,  1,  0,  1,  0,  0,  0,  1,
                1,  1,  0,  1,  1,  0,  1,  0,  0,  1,  0,
                1,  1,  0,  0,  1,  0,  0,  0,  1,  0,  0,
                0,  0,  0,  1,  1,  0,  1,  1,  0,  0,  0;

    Eigen::MatrixXi isOn_relation(11,11);

    isOn_relation.setZero();
    isOn_relation(3,5) = 1;
    isOn_relation(4,5) = 1;

    Eigen::MatrixXi coplanar_relation(11,11);

    coplanar_relation.setZero();

    vector<Eigen::MatrixXi> g1_relations;

    g1_relations.push_back( isOn_relation );
    g1_relations.push_back( coplanar_relation );

    Eigen::VectorXi g1_groundTruth(11);

    g1_groundTruth << 4, 0, 1, 2, 2, 6, 1, 1, 5, 0, 3;

    fillGraph( graph1, g1_nf, simpleNodeType1Ptr,
                  g1_adj, simpleEdgeType1Ptr, g1_relations,
                  g1_groundTruth, groundTruth1 );

    graphs.push_back( graph1 );
    groundTruths.push_back( groundTruth1 );

    cout << graph1 << endl;

/*--------------------------------- Graph 2 ----------------------------------*/

    cout << "Graph 2" << endl;

    CGraph graph2;
    std::map<size_t,size_t> groundTruth2;

    Eigen::MatrixXd g2_nf(5,5);

    g2_nf << 0, 0.745944,   1.20098,    1.68726,    1,
             1, 0.523566,   0.255477,   1.72744,    1,
             0, 0,          1.49268,    2.54707,    1,
             1, 0.359525,   0.268375,   2.8157,     1,
             0, 0.446692,   0.129895,   1,          1;

    Eigen::MatrixXi g2_adj(5,5);

    g2_adj << 0,  1,  0,  1,  1,
            1,  0,  1,  1,  0,
            0,  1,  0,  1,  1,
            1,  1,  1,  0,  1,
            1,  0,  1,  1,  0;

    isOn_relation.resize(5,5);

    isOn_relation.setZero();

    coplanar_relation.resize(5,5);

    coplanar_relation.setZero();

    vector<Eigen::MatrixXi> g2_relations;

    g2_relations.push_back( isOn_relation );
    g2_relations.push_back( coplanar_relation );

    Eigen::VectorXi g2_groundTruth(5);

    g2_groundTruth << 2, 3, 0, 3, 5;

    fillGraph( graph2, g2_nf, simpleNodeType1Ptr,
               g2_adj, simpleEdgeType1Ptr, g2_relations,
               g2_groundTruth, groundTruth2 );

    graphs.push_back( graph2 );
    groundTruths.push_back( groundTruth2 );


///*--------------------------------- Graph 3 ----------------------------------*/

    cout << "Graph 3" << endl;

    CGraph graph3;
    std::map<size_t,size_t> groundTruth3;

    Eigen::MatrixXd g3_nf(10,5);

    g3_nf << 1, 1.56711,    3.42284,    2.00889, 1,
             1, 1.02852,    0.339804,   1.54119, 1,
             1, 1.02507,    0.317727,   1.77383, 1,
             0, 0.880216,   1.45163,    2.04593, 1,
             1, 1.04219,    0.229974,   1.77708, 1,
             1, 1.66558,    0.171681,   2.3654,  1,
             0, 0.488131,   0.233171,   1.51503, 1,
             1, 0.699061,   0.120062,   1.55154, 1,
             0, 0,          2.84036,    1.99605, 1,
             1, 0.167627,   0.352816,   3.80501, 1;

    Eigen::MatrixXi g3_adj(10,10);

    g3_adj <<   0,  1,  1,  1,  1,  1,  0,  0,  0,  1,
            1,  0,  1,  1,  0,  0,  0,  0,  0,  0,
            1,  1,  0,  1,  1,  1,  1,  1,  0,  1,
            1,  1,  1,  0,  1,  1,  1,  1,  0,  1,
            1,  0,  1,  1,  0,  1,  1,  1,  0,  1,
            1,  0,  1,  1,  1,  0,  0,  0,  0,  0,
            0,  0,  1,  1,  1,  0,  0,  1,  1,  0,
            0,  0,  1,  1,  1,  0,  1,  0,  1,  0,
            0,  0,  0,  0,  0,  0,  1,  1,  0,  1,
            1,  0,  1,  1,  1,  0,  0,  0,  1,  0;

    isOn_relation.resize(10,10);
    isOn_relation.setZero();
    isOn_relation(1,3) = 1;
    isOn_relation(2,3) = 1;
    isOn_relation(3,4) = 1;

    coplanar_relation.resize(10,10);

    coplanar_relation.setZero();

    vector<Eigen::MatrixXi> g3_relations;

    g3_relations.push_back( isOn_relation );
    g3_relations.push_back( coplanar_relation );

    Eigen::VectorXi g3_groundTruth(10);

    g3_groundTruth << 1, 6, 6, 2, 9, 10, 5, 4, 0, 1;

    fillGraph( graph3, g3_nf, simpleNodeType1Ptr,
                  g3_adj, simpleEdgeType1Ptr, g3_relations,
                  g3_groundTruth, groundTruth3 );

    graphs.push_back( graph3 );
    groundTruths.push_back( groundTruth3 );

///*--------------------------------- Graph 4 ----------------------------------*/

    cout << "Graph 4" << endl;

    CGraph graph4;
    std::map<size_t,size_t> groundTruth4;

    Eigen::MatrixXd g4_nf(7,5);

    g4_nf << 1, 1.58673,    2.5301,     1.79962, 1,
             1, 1.01892,    0.198802,   1.46393, 1,
             1, 1.00455,    0.230172,   1.67413, 1,
             0, 0.744138,   0.89911,    1.57856, 1,
             0, 0.477457,   0.187906,   1.87622, 1,
             1, 0.7026,     0.113952,   1.44738, 1,
             0, 0,          2.75497,    1.87592, 1;

    Eigen::MatrixXi g4_adj(7,7);

    g4_adj <<   0,  1,  1,  1,  0,  0,  0,
                1,  0,  1,  1,  1,  1,  0,
                1,  1,  0,  1,  1,  1,  0,
                1,  1,  1,  0,  1,  1,  0,
                0,  1,  1,  1,  0,  1,  1,
                0,  1,  1,  1,  1,  0,  1,
                0,  0,  0,  0,  1,  1,  0;

    isOn_relation.resize(7,7);
    isOn_relation.setZero();
    isOn_relation(1,3) = 1;
    isOn_relation(2,3) = 1;

    coplanar_relation.resize(7,7);

    coplanar_relation.setZero();

    vector<Eigen::MatrixXi> g4_relations;

    g4_relations.push_back( isOn_relation );
    g4_relations.push_back( coplanar_relation );

    Eigen::VectorXi g4_groundTruth(7);

    g4_groundTruth << 1, 6, 9, 2, 5, 4, 0;

    fillGraph( graph4, g4_nf, simpleNodeType1Ptr,
                  g4_adj, simpleEdgeType1Ptr, g4_relations,
                  g4_groundTruth, groundTruth4 );

    graphs.push_back( graph4 );
    groundTruths.push_back( groundTruth4 );

///*--------------------------------- Graph 5 ----------------------------------*/

    cout << "Graph 5" << endl;

    // Desktop 6
    CGraph graph5;
    std::map<size_t,size_t> groundTruth5;

    Eigen::MatrixXd g5_nf(8,5);

    g5_nf << 1, 1.10316,    0.363647,   1.61694,    1,
             1, 1.00384,    0.23474,    2.7587,     1,
             1, 0.988903,   0.118134,   1,          1,
             0, 0.789307,   1.62451,    2.07762,    1,
             1, 0.672498,   1.8316,     1.78692,    1,
             1, 0.976089,   0.244898,   1,          1,
             0, 0.502879,   0.186037,   2.29688,    1,
             0, 0,          2.50486,    1.43262,    1;

    Eigen::MatrixXi g5_adj(8,8);

    g5_adj <<   0,  1,  1,  1,  1,  1,  0,  0,
                1,  0,  1,  1,  1,  0,  0,  0,
                1,  1,  0,  1,  0,  0,  0,  0,
                1,  1,  1,  0,  1,  1,  1,  0,
                1,  1,  0,  1,  0,  1,  1,  1,
                1,  0,  0,  1,  1,  0,  1,  0,
                0,  0,  0,  1,  1,  1,  0,  0,
                0,  0,  0,  0,  1,  0,  0,  0;

    isOn_relation.resize(8,8);
    isOn_relation.setZero();
    isOn_relation(0,3) = 1;
    isOn_relation(2,3) = 1;

    coplanar_relation.resize(8,8);

    coplanar_relation.setZero();

    vector<Eigen::MatrixXi> g5_relations;

    g5_relations.push_back( isOn_relation );
    g5_relations.push_back( coplanar_relation );

    Eigen::VectorXi g5_groundTruth(8);

    g5_groundTruth << 6, 1, 8, 2, 1, 1, 5, 0;

    fillGraph( graph5, g5_nf, simpleNodeType1Ptr,
                  g5_adj, simpleEdgeType1Ptr, g5_relations,
                  g5_groundTruth, groundTruth5 );

    graphs.push_back( graph5 );
    groundTruths.push_back( groundTruth5 );


///*--------------------------------- Graph 6 ----------------------------------*/

    cout << "Graph 6" << endl;

    // Desktop 7
    CGraph graph6;
    std::map<size_t,size_t> groundTruth6;

    Eigen::MatrixXd g6_nf(7,5);

    g6_nf << 1, 0.975437,   1.21382,    2.28555,    1,
             1, 0.951433,   0.270196,   2.29035,    1,
             0, 0.766445,   1.00624,    1.6777,     1,
             0, 0,          1.13219,    1.64994,    1,
             1, 0.985712,   0.208164,   1.67471,    1,
             0, 0.499913,   0.208579,   1.95149,    1,
             1, 0.970966,   0.16066,    1,          1;

    Eigen::MatrixXi g6_adj(7,7);

    g6_adj <<   0,  1,  1,  1,  0,  0,  1,
                1,  0,  1,  0,  1,  1,  1,
                1,  1,  0,  0,  1,  1,  1,
                1,  0,  0,  0,  0,  1,  0,
                0,  1,  1,  0,  0,  1,  0,
                0,  1,  1,  1,  1,  0,  0,
                1,  1,  1,  0,  0,  0,  0;

    isOn_relation.resize(7,7);
    isOn_relation.setZero();
    isOn_relation(2,6) = 1;

    coplanar_relation.resize(7,7);

    coplanar_relation.setZero();

    vector<Eigen::MatrixXi> g6_relations;

    g6_relations.push_back( isOn_relation );
    g6_relations.push_back( coplanar_relation );

    Eigen::VectorXi g6_groundTruth(7);

    g6_groundTruth << 1, 1, 2, 0, 4, 5, 6;

    fillGraph( graph6, g6_nf, simpleNodeType1Ptr,
                  g6_adj, simpleEdgeType1Ptr, g6_relations,
                  g6_groundTruth, groundTruth6 );

    graphs.push_back( graph6 );
    groundTruths.push_back( groundTruth6 );


///*--------------------------------- Graph 7 ----------------------------------*/

    cout << "Graph 7" << endl;

    // Desktop 8
    CGraph graph7;
    std::map<size_t,size_t> groundTruth7;

    Eigen::MatrixXd g7_nf(7,5);

    g7_nf << 1, 1.08949,    0.44,       1.51331,    1,
             1, 1.07257,    0.144868,   1,          1,
             0, 0.802159,   1.19101,    1.78961,    1,
             1, 0.728912,   0.128203,   2.15983,    1,
             0, 0,          3.7626,     2.86856,    1,
             0, 0.0142013,  0.175163,   2.24823,    1,
             0, 0.540925,   0.205526,   1,          1;

    Eigen::MatrixXi g7_adj(7,7);

    g7_adj << 0,  1,  1,  1,  0,  0,  1,
            1,  0,  1,  0,  0,  0,  0,
            1,  1,  0,  1,  0,  0,  1,
            1,  0,  1,  0,  0,  0,  1,
            0,  0,  0,  0,  0,  1,  1,
            0,  0,  0,  0,  1,  0,  1,
            1,  0,  1,  1,  1,  1,  0;

    isOn_relation.resize(7,7);
    isOn_relation.setZero();
    isOn_relation(0,2) = 1;
    isOn_relation(1,2) = 1;

    coplanar_relation.resize(7,7);

    coplanar_relation.setZero();

    vector<Eigen::MatrixXi> g7_relations;

    g7_relations.push_back( isOn_relation );
    g7_relations.push_back( coplanar_relation );

    Eigen::VectorXi g7_groundTruth(7);

    g7_groundTruth << 6, 6, 2, 4, 0, 0, 5;

    fillGraph( graph7, g7_nf, simpleNodeType1Ptr,
                  g7_adj, simpleEdgeType1Ptr, g7_relations,
                  g7_groundTruth, groundTruth7 );

    graphs.push_back( graph7 );
    groundTruths.push_back( groundTruth7 );


///*--------------------------------- Graph 8 ----------------------------------*/


    cout << "Graph 8" << endl;

    // Desktop 9
    CGraph graph8;
    std::map<size_t,size_t> groundTruth8;

    Eigen::MatrixXd g8_nf(5,5);

    g8_nf << 1, 1.0398,     1.45393,    1.85835,    1,
             0, 0.687862,   1.05335,    1.44245,    1,
             0, 0.476001,   0.17945,    1,          1,
             1, 0.150004,   0.163443,   1.72806,    1,
             0, 0,          2.11644,    3.64183,    1;

    Eigen::MatrixXi g8_adj(5,5);

    g8_adj << 0,  1,  0,  0,  0,
            1,  0,  1,  1,  0,
            0,  1,  0,  1,  1,
            0,  1,  1,  0,  1,
            0,  0,  1,  1,  0;

    isOn_relation.resize(5,5);
    isOn_relation.setZero();

    coplanar_relation.resize(5,5);

    coplanar_relation.setZero();

    vector<Eigen::MatrixXi> g8_relations;

    g8_relations.push_back( isOn_relation );
    g8_relations.push_back( coplanar_relation );

    Eigen::VectorXi g8_groundTruth(5);

    g8_groundTruth << 1, 2, 5, 1, 0;

    fillGraph( graph8, g8_nf, simpleNodeType1Ptr,
                  g8_adj, simpleEdgeType1Ptr, g8_relations,
                  g8_groundTruth, groundTruth8 );

    graphs.push_back( graph8 );
    groundTruths.push_back( groundTruth8 );




///*--------------------------------- Graph 9 ----------------------------------*/

    cout << "Graph 9" << endl;

    // Desktop 11
    CGraph graph9;
    std::map<size_t,size_t> groundTruth9;

    Eigen::MatrixXd g9_nf(6,5);

    g9_nf << 1, 1.08032,    0.175311,   1.59692, 1,
             1, 1.04474,    0.153065,   1.75199, 1,
             0, 0.802788,   1.36259,    2.70243, 1,
             1, 0.727563,   0.115821,   1.56757, 1,
             0, 0,          2.24629,    1.73137, 1,
             0, 0.516504,   0.165597,   1,       1;

    Eigen::MatrixXi g9_adj(6,6);

    g9_adj << 0,  1,  1,  1,  0,  0,
             1,  0,  1,  0,  0,  0,
             1,  1,  0,  1,  0,  1,
             1,  0,  1,  0,  1,  1,
             0,  0,  0,  1,  0,  1,
             0,  0,  1,  1,  1,  0;

    isOn_relation.resize(6,6);
    isOn_relation.setZero();
    isOn_relation(0,2) = 1;

    coplanar_relation.resize(6,6);

    coplanar_relation.setZero();

    vector<Eigen::MatrixXi> g9_relations;

    g9_relations.push_back( isOn_relation );
    g9_relations.push_back( coplanar_relation );

    Eigen::VectorXi g9_groundTruth(6);

    g9_groundTruth << 6, 1, 2, 4, 0, 5;

    fillGraph( graph9, g9_nf, simpleNodeType1Ptr,
                  g9_adj, simpleEdgeType1Ptr, g9_relations,
                  g9_groundTruth, groundTruth9 );

    graphs.push_back( graph9 );
    groundTruths.push_back( groundTruth9 );

///*--------------------------------- Graph 10 ----------------------------------*/

    cout << "Graph 10" << endl;

    // Desktop 13
    CGraph graph10;
    std::map<size_t,size_t> groundTruth10;

    Eigen::MatrixXd g10_nf(7,5);

    g10_nf << 1, 1.13981,   0.613381,   1.46317,    1,
              1, 1.01258,   0.167784,   1.47751,    1,
              0, 0.772106,  1.55737,    3.7527,     1,
              1, 1.11485,   0.201305,   2.29086,    1,
              0, 0.487854,  0.161754,   1.53537,    1,
              0, 0,         0.70792,    2.77777,    1,
              0, 0.0221937, 0.310503,   1.72698,    1;

    Eigen::MatrixXi g10_adj(7,7);

    g10_adj << 0,  1,  1,  1,  0,  0,  0,
                1,  0,  1,  1,  0,  0,  0,
                1,  1,  0,  1,  1,  0,  0,
                1,  1,  1,  0,  1,  0,  0,
                0,  0,  1,  1,  0,  1,  1,
                0,  0,  0,  0,  1,  0,  1,
                0,  0,  0,  0,  1,  1,  0;

    isOn_relation.resize(7,7);
    isOn_relation.setZero();
    isOn_relation(1,2) = 1;
    isOn_relation(2,3) = 1;

    coplanar_relation.resize(7,7);

    coplanar_relation.setZero();

    vector<Eigen::MatrixXi> g10_relations;

    g10_relations.push_back( isOn_relation );
    g10_relations.push_back( coplanar_relation );

    Eigen::VectorXi g10_groundTruth(7);

    g10_groundTruth << 1, 6, 2, 8, 5, 0, 0;

    fillGraph( graph10, g10_nf, simpleNodeType1Ptr,
                  g10_adj, simpleEdgeType1Ptr, g10_relations,
                  g10_groundTruth, groundTruth10 );

    graphs.push_back( graph10 );
    groundTruths.push_back( groundTruth10 );


///*--------------------------------- Graph 11 ----------------------------------*/

    cout << "Graph 11" << endl;

    // Desktop 14
    CGraph graph11;
    std::map<size_t,size_t> groundTruth11;

    Eigen::MatrixXd g11_nf(3,5);

    g11_nf << 1, 1.39389,   1.07869,    3.04842, 1,
              0, 0.724976,  0.627546,   3.18692, 1,
              1, 1.02144,   0.168219,   1.53329, 1;

    Eigen::MatrixXi g11_adj(3,3);

    g11_adj << 0,  1,  1,
               1,  0,  1,
               1,  1,  0;

    isOn_relation.resize(3,3);
    isOn_relation.setZero();
    isOn_relation(1,2) = 1;

    coplanar_relation.resize(3,3);

    coplanar_relation.setZero();

    vector<Eigen::MatrixXi> g11_relations;

    g11_relations.push_back( isOn_relation );
    g11_relations.push_back( coplanar_relation );

    Eigen::VectorXi g11_groundTruth(3);

    g11_groundTruth << 1, 2, 6;

    fillGraph( graph11, g11_nf, simpleNodeType1Ptr,
                  g11_adj, simpleEdgeType1Ptr, g11_relations,
                  g11_groundTruth, groundTruth11 );

    graphs.push_back( graph11 );
    groundTruths.push_back( groundTruth11 );


///*--------------------------------- Graph 12 ----------------------------------*/

    cout << "Graph 12" << endl;

    // Desktop 15
    CGraph graph12;
    std::map<size_t,size_t> groundTruth12;

    Eigen::MatrixXd g12_nf(9,5);

    g12_nf << 1, 0.890949,  3.09357,    2.35317, 1,
              0, 0.337975,  0.284948,   1.73898, 1,
              1, 0.722686,  0.397614,   1.45951, 1,
              0, 0.619682,  1.56466,    2.28344, 1,
              1, 0.404655,  0.167949,   1,       1,
              1, 0.726681,  0.198501,   1.52176, 1,
              1, 0.876247,  0.182265,   1.92814, 1,
              1, 0.639947,  0.133658,   2.02595, 1,
              0, 0,         0.36366,    1,       1;

    Eigen::MatrixXi g12_adj(9,9);

    g12_adj << 0,  1,  1,  0,  1,  1,  0,  0,  0,
             1,  0,  1,  1,  1,  0,  0,  0,  0,
             1,  1,  0,  1,  1,  0,  1,  0,  0,
             0,  1,  1,  0,  1,  1,  1,  1,  0,
             1,  1,  1,  1,  0,  0,  1,  0,  0,
             1,  0,  0,  1,  0,  0,  0,  0,  0,
             0,  0,  1,  1,  1,  0,  0,  0,  0,
             0,  0,  0,  1,  0,  0,  0,  0,  1,
             0,  0,  0,  0,  0,  0,  0,  1,  0;

    isOn_relation.resize(9,9);
    isOn_relation.setZero();
    isOn_relation(3,6) = 1;

    coplanar_relation.resize(9,9);

    coplanar_relation.setZero();

    vector<Eigen::MatrixXi> g12_relations;

    g12_relations.push_back( isOn_relation );
    g12_relations.push_back( coplanar_relation );

    Eigen::VectorXi g12_groundTruth(9);

    g12_groundTruth << 1, 5, 4, 2, 3, 1, 6, 4, 0;

    fillGraph( graph12, g12_nf, simpleNodeType1Ptr,
                  g12_adj, simpleEdgeType1Ptr, g12_relations,
                  g12_groundTruth, groundTruth12 );

    graphs.push_back( graph12 );
    groundTruths.push_back( groundTruth12 );


///*--------------------------------- Graph 13 ----------------------------------*/

//    Eigen::MatrixXi g13_adj(11,11);
//, 0,  1,  1,  1,  1,  1,  0,  1,  1,  0
//, 1,  0,  1,  0,  0,  0,  0,  1,  1,  0
//, 1,  1,  0,  0,  0,  0,  0,  0,  0,  0
//, 1,  0,  0,  0,  1,  1,  1,  1,  0,  1
//, 1,  0,  0,  1,  0,  1,  1,  1,  1,  1
//, 1,  0,  0,  1,  1,  0,  1,  0,  0,  0
//, 0,  0,  0,  1,  1,  1,  0,  1,  0,  1
//, 1,  1,  0,  1,  1,  0,  1,  0,  1,  0
//, 1,  1,  0,  0,  1,  0,  0,  1,  0,  0
//, 0,  0,  0,  1,  1,  0,  1,  0,  0,  0

///*--------------------------------- Graph 14 ----------------------------------*/

//    Eigen::MatrixXi g14_adj(11,11);
//, 0,  1,  0,  1,  1,  1
//, 1,  0,  1,  1,  0,  0
//, 0,  1,  0,  1,  1,  0
//, 1,  1,  1,  0,  1,  0
//, 1,  0,  1,  1,  0,  0
//, 1,  0,  0,  0,  0,  0

///*--------------------------------- Graph 15 ----------------------------------*/

//    Eigen::MatrixXi g15_adj(11,11);
//, 0,  1,  1,  1,  0,  0,  0,  1
//, 1,  0,  1,  1,  0,  0,  0,  0
//, 1,  1,  0,  1,  1,  1,  0,  1
//, 1,  1,  1,  0,  1,  1,  0,  1
//, 0,  0,  1,  1,  0,  1,  1,  0
//, 0,  0,  1,  1,  1,  0,  1,  0
//, 0,  0,  0,  0,  1,  1,  0,  1
//, 1,  0,  1,  1,  0,  0,  1,  0

///*--------------------------------- Graph 16 ----------------------------------*/

//    Eigen::MatrixXi g16_adj(11,11);
//, 0,  1,  1,  0,  0,  0
//, 1,  0,  1,  1,  1,  0
//, 1,  1,  0,  1,  1,  0
//, 0,  1,  1,  0,  1,  1
//, 0,  1,  1,  1,  0,  1
//, 0,  0,  0,  1,  1,  0

///*--------------------------------- Graph 17 ----------------------------------*/

//    Eigen::MatrixXi g17_adj(11,11);
//, 0,  1,  1,  1,  1,  0,  0
//, 1,  0,  1,  1,  0,  0,  0
//, 1,  1,  0,  1,  1,  1,  0
//, 1,  1,  1,  0,  1,  1,  1
//, 1,  0,  1,  1,  0,  1,  0
//, 0,  0,  1,  1,  1,  0,  0
//, 0,  0,  0,  1,  0,  0,  0

///*--------------------------------- Graph 18 ----------------------------------*/

//    Eigen::MatrixXi g18_adj(11,11);
//, 0,  1,  1,  1,  0,  0,  1,  1
//, 1,  0,  1,  0,  1,  1,  1,  0
//, 1,  1,  0,  0,  1,  1,  1,  1
//, 1,  0,  0,  0,  0,  1,  0,  0
//, 0,  1,  1,  0,  0,  1,  0,  0
//, 0,  1,  1,  1,  1,  0,  0,  0
//, 1,  1,  1,  0,  0,  0,  0,  0
//, 1,  0,  1,  0,  0,  0,  0,  0

///*--------------------------------- Graph 19 ----------------------------------*/

//    Eigen::MatrixXi g19_adj(11,11);
//, 0,  1,  0,  0,  0,  0
//, 1,  0,  1,  0,  0,  1
//, 0,  1,  0,  0,  0,  1
//, 0,  0,  0,  0,  1,  1
//, 0,  0,  0,  1,  0,  1
//, 0,  1,  1,  1,  1,  0

///*--------------------------------- Graph 20 ----------------------------------*/

//    Eigen::MatrixXi g20_adj(11,11);
//, 0,  1,  0,  0,  0
//, 1,  0,  1,  1,  0
//, 0,  1,  0,  1,  1
//, 0,  1,  1,  0,  1
//, 0,  0,  1,  1,  0

///*--------------------------------- Graph 21 ----------------------------------*/

//    Eigen::MatrixXi g21_adj(11,11);
//, 0,  1,  1,  1,  0,  0,  0
//, 1,  0,  1,  0,  0,  0,  0
//, 1,  1,  0,  1,  0,  1,  1
//, 1,  0,  1,  0,  1,  1,  0
//, 0,  0,  0,  1,  0,  1,  0
//, 0,  0,  1,  1,  1,  0,  0
//, 0,  0,  1,  0,  0,  0,  0

///*--------------------------------- Graph 22 ----------------------------------*/

//    Eigen::MatrixXi g22_adj(11,11);
//, 0,  1,  1,  0,  0
//, 1,  0,  1,  0,  0
//, 1,  1,  0,  1,  0
//, 0,  0,  1,  0,  1
//, 0,  0,  0,  1,  1

///*--------------------------------- Graph 23 ----------------------------------*/

//    Eigen::MatrixXi g23_adj(11,11);
//, 0,  1,  1
//, 1,  0,  1
//, 1,  1,  0

///*--------------------------------- Graph 24 ----------------------------------*/

//    Eigen::MatrixXi g24_adj(11,11);

//    g24_adj <<  0,  1,  1,  0,  1,  1,  0,  0,  0,
//                1,  0,  1,  1,  1,  0,  0,  0,  0,
//                1,  1,  0,  1,  1,  0,  1,  0,  0,
//                0,  1,  1,  0,  1,  1,  1,  1,  0,
//                1,  1,  1,  1,  0,  0,  1,  0,  0,
//                1,  0,  0,  1,  0,  0,  0,  0,  0,
//                0,  0,  1,  1,  1,  0,  0,  0,  0,
//                0,  0,  0,  1,  0,  0,  0,  0,  1,
//                0,  0,  0,  0,  0,  0,  0,  1,  0;

///*--------------------------------- Graph 25 ----------------------------------*/

//    Eigen::MatrixXi g25_adj(11,11);

//    g25_adj <<  0,  1,  1,  0,  0,
//                1,  0,  1,  1,  1,
//                1,  1,  0,  0,  0,
//                0,  1,  0,  0,  1,
//                0,  1,  0,  1,  0;

    static boost::mt19937 rng;
    rng.seed(std::time(0));

    size_t N_graphsForTraining = 9;

    size_t absoluteSuccess_Greedy  = 0;
    size_t absoluteSuccess_ICM     = 0;
    size_t absoluteSuccess_AlphaExpansion = 0;
    size_t absoluteSuccess_AlphaBetaSwap  = 0;
    size_t absoluteSuccess_LBP = 0;
    size_t absoluteSuccess_TRP = 0;
    size_t absoluteSuccess_RBP = 0;
    size_t absoluteNumberOfNodes = 0;

    size_t N_repetitions = 100;

    for ( size_t rep = 0; rep < N_repetitions; rep++ )
    {

    vector<size_t> graphs_to_train;
    size_t N_graphsAdded       = 0;

    while ( N_graphsAdded < N_graphsForTraining )
    {
        boost::uniform_int<> int_generator(0,11);
        int rand = int_generator(rng);

        if ( std::find(graphs_to_train.begin(),graphs_to_train.end(),rand)
             == graphs_to_train.end() )
        {
            graphs_to_train.push_back(rand);
            N_graphsAdded++;
        }
    }

    vector<size_t> graphs_to_test;

    for ( size_t i = 0; i < graphs.size(); i++ )
        if ( std::find(graphs_to_train.begin(),graphs_to_train.end(), i)
             == graphs_to_train.end() )
            graphs_to_test.push_back(i);

    cout << "Graphs to test: ";

    for ( size_t i = 0; i < graphs_to_test.size(); i++)
        cout << graphs_to_test[i] << " ";

    cout << endl;


//    graphs_to_train.push_back(0);
//    graphs_to_train.push_back(1);
//    graphs_to_train.push_back(2);
//    graphs_to_train.push_back(3);
//    graphs_to_train.push_back(4);
//    graphs_to_train.push_back(5);
//    graphs_to_train.push_back(6);
//    graphs_to_train.push_back(7);
//    graphs_to_train.push_back(8);
//    graphs_to_train.push_back(9);
//    graphs_to_train.push_back(10);


//    graphs_to_test.push_back(11);

    for ( size_t i = 0; i < graphs_to_train.size(); i++ )
    {
        trainingDataset.addGraph( graphs[graphs_to_train[i]] );
        trainingDataset.addGraphGroundTruth( groundTruths[graphs_to_train[i]] );
    }


/*------------------------------------------------------------------------------
 *
 *                               TRAINING!
 *
 *----------------------------------------------------------------------------*/

    UPGMpp::TTrainingOptions to;
    to.l2Regularization     = true;
    to.nodeLambda           = 10;
    to.edgeLambda           = 15;
    to.showTrainedWeights   = false;
    to.showTrainingProgress = false;

    cout << "------------------------------------------------------" << endl;
    cout << "                      TRAINING" << endl;
    cout << "------------------------------------------------------" << endl;

    trainingDataset.setTrainingOptions( to );
    int res = trainingDataset.train();

    if (res!=0) continue;


/*------------------------------------------------------------------------------
 *
 *              PREPARE A GRAPH FOR PERFORMING DECODING AND INFERENCE
 *
 *----------------------------------------------------------------------------*/

    cout << "------------------------------------------------------" << endl;
    cout << "                      TESTING" << endl;
    cout << "------------------------------------------------------" << endl;

    for ( size_t i = 0; i < graphs_to_test.size(); i++ )
    {

        graphs[graphs_to_test[i]].computePotentials();

    /*------------------------------------------------------------------------------
     *
     *                               DECODING!
     *
     *----------------------------------------------------------------------------*/

        cout << endl;
        cout << "------------------------------------------------------" << endl;
        cout << "                      DECODING" << endl;
        cout << "------------------------------------------------------" << endl;


        CICMInferenceMAP       decodeICM;
        CICMGreedyInferenceMAP decodeICMGreedy;
        CAlphaExpansionInferenceMAP decodeAlphaExpansion;
        CAlphaBetaSwapInferenceMAP decodeAlphaBetaSawp;
        CLBPInferenceMAP      decodeLBP;
        CTRPBPInferenceMAP    decodeTRPBP;
        CRBPInferenceMAP      decodeRBP;

        double totalSuccess_Greedy  = 0;
        double totalSuccess_ICM     = 0;
        double totalSuccess_AlphaExpansion = 0;
        double totalSuccess_AlphaBetaSwap  = 0;
        double totalSuccess_LBP = 0;
        double totalSuccess_TRP = 0;
        double totalSuccess_RBP = 0;

        TInferenceOptions options;
        options.maxIterations = 100;

        std::map<size_t,size_t> resultsMap;
        std::map<size_t,size_t>::iterator it;

        //std::cout << "           RESULTS ICM " << std::endl;
        //std::cout << "-----------------------------------" << std::endl;

        decodeICM.setOptions( options );
        decodeICM.infer( graphs[graphs_to_test[i]], resultsMap );

        for ( it = resultsMap.begin(); it != resultsMap.end(); it++ )
            if ( it->second == groundTruths[graphs_to_test[i]][ it->first ])
                totalSuccess_ICM++;

        //showResults( resultsMap );

        //std::cout << "-----------------------------------" << std::endl;
        //std::cout << "         RESULTS ICM GREEDY" << std::endl;
        //std::cout << "-----------------------------------" << std::endl;

        decodeICMGreedy.setOptions( options );
        decodeICMGreedy.infer( graphs[graphs_to_test[i]], resultsMap );

        for ( it = resultsMap.begin(); it != resultsMap.end(); it++ )
            if ( it->second == groundTruths[graphs_to_test[i]][ it->first ])
                totalSuccess_Greedy++;

        //showResults( resultsMap );

        //std::cout << "-----------------------------------" << std::endl;
        //std::cout << "      RESULTS ALPHA-EXPANSIONS" << std::endl;
        //std::cout << "-----------------------------------" << std::endl;

        options.maxIterations = 10000;
        decodeAlphaExpansion.setOptions( options );
        decodeAlphaExpansion.infer( graphs[graphs_to_test[i]], resultsMap );

        for ( it = resultsMap.begin(); it != resultsMap.end(); it++ )
            if ( it->second == groundTruths[graphs_to_test[i]][ it->first ])
                totalSuccess_AlphaExpansion++;

        //showResults( resultsMap );

        //std::cout << "-----------------------------------" << std::endl;
        //std::cout << "        RESULTS ALPHA-BETA" << std::endl;
        //std::cout << "-----------------------------------" << std::endl;

        options.maxIterations = 10000;
        decodeAlphaBetaSawp.setOptions( options );
        decodeAlphaBetaSawp.infer( graphs[graphs_to_test[i]], resultsMap );

        for ( it = resultsMap.begin(); it != resultsMap.end(); it++ )
        {
            if ( it->second == groundTruths[graphs_to_test[i]][ it->first ])
                totalSuccess_AlphaBetaSwap++;
        }

        //showResults( resultsMap );

        //std::cout << "-----------------------------------" << std::endl;
        //std::cout << "        RESULTS LBP" << std::endl;
        //std::cout << "-----------------------------------" << std::endl;

        options.maxIterations = 10000;
        decodeLBP.setOptions( options );
        decodeLBP.infer( graphs[graphs_to_test[i]], resultsMap );

        for ( it = resultsMap.begin(); it != resultsMap.end(); it++ )
            if ( it->second == groundTruths[graphs_to_test[i]][ it->first ])
                totalSuccess_LBP++;


        //showResults( resultsMap );

        //std::cout << "-----------------------------------" << std::endl;
        //std::cout << "        RESULTS TRP" << std::endl;
        //std::cout << "-----------------------------------" << std::endl;

        options.maxIterations = 10000;
        decodeTRPBP.setOptions( options );
        decodeTRPBP.infer( graphs[graphs_to_test[i]], resultsMap );

        for ( it = resultsMap.begin(); it != resultsMap.end(); it++ )
            if ( it->second == groundTruths[graphs_to_test[i]][ it->first ])
                totalSuccess_TRP++;

        //showResults( resultsMap );

        //std::cout << "-----------------------------------" << std::endl;
        //std::cout << "         RESULTS RBP" << std::endl;
        //std::cout << "-----------------------------------" << std::endl;

        options.maxIterations = 10000;
        decodeRBP.setOptions( options );
        //decodeRBP.infer( graphs[graphs_to_test[i]], resultsMap );

        for ( it = resultsMap.begin(); it != resultsMap.end(); it++ )
            if ( it->second == groundTruths[graphs_to_test[i]][ it->first ])
                totalSuccess_RBP++;

        //showResults( resultsMap );

        //std::cout << "-----------------------------------" << std::endl;

        double totalNumberOfNodes = graphs[graphs_to_test[i]].getNodes().size();

        //cout << "Total MaxNodePot success: " << 100*(totalSuccess_MaxNodePot / totalNumberOfNodes) << "%" << endl;
        cout << "Total Greedy     success: " << 100*(totalSuccess_Greedy / totalNumberOfNodes) << "%" << endl;
        cout << "Total ICM        success: " << 100*(totalSuccess_ICM / totalNumberOfNodes) << "%" << endl;
        //cout << "Total Exact      success: " << 100*(totalSuccess_Exact / totalNumberOfNodes) << "%" << endl;
        cout << "Total AlphaExpan success: " << 100*(totalSuccess_AlphaExpansion / totalNumberOfNodes) << "%" << endl;
        cout << "Total AlphaBetaS success: " << 100*(totalSuccess_AlphaBetaSwap / totalNumberOfNodes) << "%" << endl;
        cout << "Total LBP        success: " << 100*(totalSuccess_LBP / totalNumberOfNodes) << "%" << endl;
        cout << "Total TRP        success: " << 100*(totalSuccess_TRP / totalNumberOfNodes) << "%" << endl;
        cout << "Total RBP        success: " << 100*(totalSuccess_RBP / totalNumberOfNodes) << "%" << endl;

        absoluteNumberOfNodes           += totalNumberOfNodes;
        absoluteSuccess_Greedy          += totalSuccess_Greedy;
        absoluteSuccess_ICM             += totalSuccess_ICM;
        absoluteSuccess_AlphaExpansion  += totalSuccess_AlphaExpansion;
        absoluteSuccess_AlphaBetaSwap   += totalSuccess_AlphaBetaSwap;
        absoluteSuccess_LBP             += totalSuccess_LBP;
        absoluteSuccess_TRP             += totalSuccess_TRP;
        absoluteSuccess_RBP             += totalSuccess_RBP;

    /*------------------------------------------------------------------------------
     *
     *                               INFERENCE!
     *
     *----------------------------------------------------------------------------*/

        /*cout << endl;
        cout << "------------------------------------------------------" << endl;
        cout << "                      INFERENCE" << endl;
        cout << "------------------------------------------------------" << endl;


        std::cout << "     LOOPY BELIEF PROPAGATION " << std::endl;
        std::cout << "-----------------------------------" << std::endl;

        CLBPInference LBPInference;

        map<size_t,VectorXd> nodeBeliefs;
        map<size_t,MatrixXd> edgeBeliefs;
        double logZ;

        LBPInference.infer( graphs[graphs_to_test[i]], nodeBeliefs, edgeBeliefs, logZ );

        map<size_t,VectorXd>::iterator itNodeBeliefs;
        for ( itNodeBeliefs = nodeBeliefs.begin(); itNodeBeliefs != nodeBeliefs.end(); itNodeBeliefs++ )
        {
            std::cout << "Node id " << itNodeBeliefs->first << " beliefs (marginals): "
                      << endl << itNodeBeliefs->second << std::endl << std::endl;
        }

        map<size_t,MatrixXd>::iterator itEdgeBeliefs;
        for ( itEdgeBeliefs = edgeBeliefs.begin(); itEdgeBeliefs != edgeBeliefs.end(); itEdgeBeliefs++ )
        {
            std::cout << "Edge id " << itEdgeBeliefs->first << " beliefs (marginals): "
                      << endl << itEdgeBeliefs->second << std::endl << std::endl;
        }

        cout << "Log Z : " << logZ << endl;*/
    }

    }

    cout << " FINAL RESULTS: " << endl;

    //cout << "Total MaxNodePot success: " << 100*(totalSuccess_MaxNodePot / totalNumberOfNodes) << "%" << endl;
    cout << "Total Greedy     success: " << 100*((double)absoluteSuccess_Greedy / absoluteNumberOfNodes) << "%" << endl;
    cout << "Total ICM        success: " << 100*((double)absoluteSuccess_ICM / absoluteNumberOfNodes) << "%" << endl;
    //cout << "Total Exact      success: " << 100*(totalSuccess_Exact / totalNumberOfNodes) << "%" << endl;
    cout << "Total AlphaExpan success: " << 100*((double)absoluteSuccess_AlphaExpansion / absoluteNumberOfNodes) << "%" << endl;
    cout << "Total AlphaBetaS success: " << 100*((double)absoluteSuccess_AlphaBetaSwap / absoluteNumberOfNodes) << "%" << endl;
    cout << "Total LBP        success: " << 100*((double)absoluteSuccess_LBP / absoluteNumberOfNodes) << "%" << endl;
    cout << "Total TRP        success: " << 100*((double)absoluteSuccess_TRP / absoluteNumberOfNodes) << "%" << endl;
    cout << "Total RBP        success: " << 100*((double)absoluteSuccess_RBP / absoluteNumberOfNodes) << "%" << endl;

    // We are ready to take a beer :)

    return 0;
}
コード例 #22
0
ファイル: kmeans.cpp プロジェクト: markusd/gpgpu
int main(int argc, char** argv)
{
	int args = 1;
#ifdef USE_OPENCL
	if (argc < 10) {
#else
	if (argc < 7) {
#endif
		std::cout << "Not enough arguments" << std::endl;
		system("pause");
		return 1;
	}

	DIM = util::toInt(argv[args++]);
	N = util::toInt(argv[args++]);
	K = util::toInt(argv[args++]);
	ITERATIONS = util::toInt(argv[args++]);
	RUNS = util::toInt(argv[args++]);
#ifdef USE_OPENCL
	AM_LWS = util::toInt(argv[args++]);
	RP_LWS = util::toInt(argv[args++]);
	CT_LWS = util::toInt(argv[args++]);

	USE_ALL_DEVICES = util::toInt(argv[args++]);
#else
	device_count = util::toInt(argv[args++]);
#endif


	std::cout << "DIM = " << DIM << std::endl;
	std::cout << "N = " << N << std::endl;
	std::cout << "K = " << K << std::endl;
	std::cout << "ITERATIONS = " << ITERATIONS << std::endl;
	std::cout << "RUNS = " << RUNS << std::endl;
#ifdef USE_OPENCL
	std::cout << "AM_LWS = " << AM_LWS << std::endl;
	std::cout << "RP_LWS = " << RP_LWS << std::endl;
	std::cout << "CT_LWS = " << CT_LWS << std::endl;
	std::cout << "USE_ALL_DEVICES = " << USE_ALL_DEVICES << std::endl << std::endl;
#else
	std::cout << "device_count = " << device_count << std::endl << std::endl;
#endif


#ifdef _WIN32
	rng.seed();
	srand(GetTickCount());
#else
	rng.seed();
	srand(getTimeMs());
#endif

	u = boost::uniform_real<float>(0.0f, 1000000.0f);
	gen = new boost::variate_generator<boost::mt19937&, boost::uniform_real<float> >(rng, u);

#ifdef USE_OPENCL
	cl_int clError = CL_SUCCESS;
	initCL();

	for (int i = 0; i < clDevices.size(); ++i) {

		clInputBuf.push_back(cl::Buffer(clContext, CL_MEM_READ_ONLY, N * DIM * sizeof(float), NULL, &clError));
		if (clError != CL_SUCCESS) std::cout << "OpenCL Error: Could not create buffer" << std::endl;

		clCentroidBuf.push_back(cl::Buffer(clContext, CL_MEM_READ_WRITE, K * DIM * sizeof(float), NULL, &clError));
		if (clError != CL_SUCCESS) std::cout << "OpenCL Error: Could not create buffer" << std::endl;

		clMappingBuf.push_back(cl::Buffer(clContext, CL_MEM_READ_WRITE, N * sizeof(int), NULL, &clError));
		if (clError != CL_SUCCESS) std::cout << "OpenCL Error: Could not create buffer" << std::endl;

		clReductionBuf.push_back(cl::Buffer(clContext, CL_MEM_WRITE_ONLY, N * sizeof(float), NULL, &clError));
		if (clError != CL_SUCCESS) std::cout << "OpenCL Error: Could not create buffer" << std::endl;

		clClusterAssignment[i].setArgs(clInputBuf[i](), clCentroidBuf[i](), clMappingBuf[i]());
		clClusterReposition[i].setArgs(clInputBuf[i](), clMappingBuf[i](), clCentroidBuf[i]());
		clClusterReposition_k[i].setArgs(clInputBuf[i](), clMappingBuf[i](), clCentroidBuf[i]());
		//clClusterReposition_k_c[i].setArgs(clInputBuf[i](), clMappingBuf[i](), clCentroidBuf[i](), clConvergedBuf[i]());
		clComputeCost[i].setArgs(clInputBuf[i](), clCentroidBuf[i](), clMappingBuf[i](), clReductionBuf[i]());

	}

	device_count = clDevices.size();
#endif

	util::Clock clock;
	clock.reset();

	for (int i = 0; i < RUNS; ++i) {
		mapping_list.push_back(NULL);
		centroids_list.push_back(NULL);
		cost_list.push_back(0.0f);
	}

	float* source = new float[N*DIM];
	for (int i = 0; i < N*DIM; ++i)
		source[i] = gen_random_float();

	input_list.push_back(source);

	for (int i = 1; i < device_count; ++i) {
		float* copy = new float[N*DIM];
		memcpy(copy, source, N*DIM*sizeof(float));
		input_list.push_back(copy);
	}

	if (device_count > 1) {
		boost::thread_group threads;

		for (int i = 0; i < device_count; ++i) {
			threads.create_thread(boost::bind(exec, i, true));
		}

		threads.join_all();
	} else {
		exec(0, false);
	}

#ifdef USE_OPENCL
	reduction_group.join_all();
#endif

	int best_result = 0;
	float best_cost = std::numeric_limits<float>::max();
	for (int i = 0; i < RUNS; ++i) {
		if (cost_list[i] < best_cost) {
			best_cost = cost_list[i];
			best_result = i;
		}
	}

	FILE *out_fdesc = fopen("centroids.out", "wb");
	fwrite((void*)centroids_list[best_result], K * DIM * sizeof(float), 1, out_fdesc);
	fclose(out_fdesc);

	out_fdesc = fopen("mapping.out", "wb");
	fwrite((void*)mapping_list[best_result], N * sizeof(int), 1, out_fdesc);
	fclose(out_fdesc);

	std::cout << "Best result is " << best_result << std::endl;

	for (int i = 0; i < device_count; ++i) {
		delete[] input_list[i];
	}

	for (int i = 0; i < RUNS; ++i) {
		delete[] mapping_list[i];
		delete[] centroids_list[i];
	}

	float now = clock.get();
	std::cout << "Total: " << now << std::endl;

	system("pause");

	return 0;
}
コード例 #23
0
ファイル: rand.cpp プロジェクト: Ibasam/IBASAM
void modify_seed(unsigned thread)
{
	rng.seed(thread);
}
コード例 #24
0
ファイル: scheduler.cpp プロジェクト: vcbin/stupidalgorithm
int scheduler::batch_run(int max_thread)
{
	// every single line of run stat file
	vector<shared_ptr<stringstream> > pvec_stat_line;// dummy file buffer to write,this buffer is to keep the run stat data output FIFO ordered for post-computation analysis convenience
	// using pointer to work around the problem that stringstream is non-copyable
	{
		try 
		{
			// load batch run script file
			batch_conf batch_conf;
			batch_conf.load_conf(m_batch_conf_path);

			vector<shared_ptr<func_base> > vec_ptr_func;// function object base class pointer
			vector<shared_ptr<para_base> > vec_ptr_para;// parameter object base class pointer
			vector<shared_ptr<alg_base> > vec_ptr_alg;// algorithm object base class pointer

			int num_alg;// number of algorithm wait to test
			num_alg=batch_conf.tasks.size();
			vec_ptr_func.resize(num_alg);
			vec_ptr_para.resize(num_alg);
			vec_ptr_alg.resize(num_alg);
			// pool algo_pool(num_alg<max_thread?num_alg:max_thread);// thread pool of algorithms
			pool algo_pool(max_thread); // thread pool of algorithms
			int cur_task_count=0;

			// batch run of specified algorithm
			int alloc_algo_res;
			int algo_type;
			string conf_path;
			bool first_task_run=true;// first time run of batch run
			bool seq_task_first_time=true;// first time run of single sequential value task
			bool different_algo=true;
			int pre_algo_type=0;
			int i,j;

			vec_task::iterator itr=batch_conf.tasks.begin();
			for ( i=0;itr!=batch_conf.tasks.end();++itr,i++ )
			{
				algo_type=(*itr).algo_code;
				conf_path=(*itr).conf_path;
				// allocate specific algorithm object dynamically
				alloc_algo_res=allocate_alg(algo_type,vec_ptr_alg[i],conf_path);
				allocate_para(algo_type,vec_ptr_para[i],conf_path);
				int load_res;
				// load configuration file data
				load_res=vec_ptr_para[i]->read_para(conf_path);
				if ( -1==load_res )
				{
					cout << "read config file ERROR!" 
						<< "\n";
					return -1;
				}

				different_algo=(pre_algo_type!=algo_type);
				if ( different_algo )
					seq_task_first_time=true;
				int func_type=vec_ptr_para[i]->get_obj_func();// test problem type
				int num_dim=vec_ptr_para[i]->get_dim();// dimension of test problem
				int stop_type=vec_ptr_para[i]->get_stop_type();// termination criterion value
				// allocate Objective Function object dynamically
				int alloc_fun_res=allocate_func(func_type,vec_ptr_func[i],num_dim);
				bool max_gen_set=has_max_gen(stop_type);

				// seed random number generator for EACH task
				gen.seed(static_cast<uint32_t>(time(0)));

				// generate output file name generic prefix
				string str_out_prefix_common;
				str_out_prefix_common=gen_out_prefix_common(algo_type,vec_ptr_func[i],vec_ptr_para[i]);
				if ( first_task_run ) 				// print overall batch run stat file title once
				{
					print_algo_stat_title(run_stat_file,max_gen_set);
					print_common_filelist_title(com_filelist);
					first_task_run=false;
				}
				// start sequential parameter valus SPECIFIC processing
				bool has_seq_val=vec_ptr_para[i]->has_seq_value();
				if ( has_seq_val )
				{
					// open sequential parameter value stat file BEFORE all combination is scheduled
					string para_stat_path=gen_para_stat_file_name(str_out_prefix_common);
					// using heap memory and smart pointer to shared the data to sub-threads
					locked_para_stat_os lps_os={shared_ptr<ostream>(new ofstream(para_stat_path.c_str())),shared_ptr<mutex>(new mutex)};
					shared_ptr<ostream> &ppara_stat_file=lps_os.pos; 
					if ( seq_task_first_time )
					{
						print_para_stat_title(*ppara_stat_file,gen_seq_var_name_str(vec_ptr_para[i]),gen_seq_var_num_str(vec_ptr_para[i]),max_gen_set);
						print_file_name(para_stat_filelist,func_type,algo_type,para_stat_path); 
						seq_task_first_time=false;
					}
					// start sequential paramter value processing
					const vector<string>& seq_var_name=vec_ptr_para[i]->get_seq_var_name_vec();
					const int seq_var_size=seq_var_name.size();
					const vector<int>& seq_dim_size=vec_ptr_para[i]->get_seq_dim_size_vec();
					int comb_num=1;
					// calc total combination number
					for ( j=0;j<seq_var_size;j++ )
						comb_num *= seq_dim_size[j];
					// generate all parameter value combination index
					vector<vector<int> > para_comb_idx;
					para_comb_idx.push_back(vector<int>(seq_var_size,0));
					int cur_dim;
					int last_dim=seq_var_size-1;
					// using this method since seq_var_size is NOT constant,
					// hence we can't use for loop to iterate
					for ( j=1;j<comb_num;j++ )
					{
						cur_dim=last_dim;
						vector<int> cur_comb_idx=para_comb_idx.back(); 
						// find approriate dim to increment index
						while ( cur_comb_idx[cur_dim] == seq_dim_size[cur_dim]-1 )
							cur_dim--;
						cur_comb_idx[cur_dim]++;// 'carry propagation'
						if ( cur_dim<last_dim )
						{
							int j;
							for ( j=cur_dim+1;j<seq_var_size;j++ )
								cur_comb_idx[j]=0;
						}
						para_comb_idx.push_back(cur_comb_idx);
					}

					// start combination schedule
					string cur_para;
					int val_idx;
					vector<int> cur_comb_idx(seq_var_size);
					int k;
					// allocate EXTRA algorithm objects andd function objects
					// Parameters object are SHARED between different parameter value combination(const)
					vector<shared_ptr<alg_base> > vec_seq_alg;
					vector<shared_ptr<func_base> > vec_seq_func;
					vector<shared_ptr<para_base> > vec_seq_para;
					vec_seq_alg.resize(comb_num);
					vec_seq_func.resize(comb_num);
					vec_seq_para.resize(comb_num);
					vec_seq_alg[0]=vec_ptr_alg[i];
					vec_seq_func[0]=vec_ptr_func[i];
					vec_seq_para[0]=vec_ptr_para[i];
					for ( k=1;k<comb_num;k++ )
					{
						allocate_alg(algo_type,vec_seq_alg[k],conf_path);
						allocate_func(func_type,vec_seq_func[k],num_dim);
						allocate_para(algo_type,vec_seq_para[k],conf_path);
						(*vec_seq_para[k])=(*vec_ptr_para[i]);// copy parameter values
					}
					for ( k=0;k<comb_num;k++ )
					{
						// alter the sequential parameter value for grouped run
						cur_comb_idx=para_comb_idx[k];
						int j;
						for ( j=0;j<seq_var_size;j++ )
						{
							cur_para=seq_var_name[j];
							val_idx=cur_comb_idx[j];
							vec_seq_para[k]->set_cur_seq_val_idx(cur_para,val_idx);
						}
						// all combination values are set
						// set task description text for output
						string str_out_prefix_para;
						str_out_prefix_para=gen_out_prefix_para(vec_seq_para[k],"_");
						vec_seq_alg[k]->set_para_val_desc(gen_seq_val_str(vec_seq_para[k]));
						string str_para_stat=gen_out_prefix_para(vec_seq_para[k],",");
						// output common stat file path list for post-computation plotting and analysis
						common_path com_out_path;// common stat file output
						gen_common_file_path(com_out_path,str_out_prefix_common,str_out_prefix_para);
						vec_seq_alg[k]->set_com_file_path(com_out_path);
						print_common_filelist(com_filelist,func_type,algo_type,com_out_path);
						print_para_stat_All_Best_Val_Path(para_stat_all_bst_val_filelist,func_type,str_para_stat,com_out_path.all_bst_val_path);// sequential parameters tuning SPECIFIC
						//  set algorithm specific stat file name
						algo_spec_output(func_type,algo_type,vec_seq_alg[k],str_out_prefix_common,str_out_prefix_para);

						// run the algo according to single parameter value combination
						vec_seq_alg[k]->set_eval_func(vec_seq_func[k]);
						vec_seq_alg[k]->load_parameter(vec_seq_para[k]);// Loading algorithm parameters from outer source

						vec_seq_alg[k]->initialize();
						// progress_timer p_t;// timer of specified algorithm
						cur_task_count++;
						output_running_prompt(cur_task_count,vec_seq_para[k]);
						pvec_stat_line.push_back(shared_ptr<stringstream>(new stringstream));// expand size by 1
						shared_ptr<stringstream> pcur_line=pvec_stat_line.back();
						shared_ptr<boost::mutex> pmutex=lps_os.pmut;
						algo_pool.schedule( 
							boost::bind(thread_fun,vec_seq_alg[k],func_type,algo_type,
							max_gen_set,has_seq_val,pcur_line,
							ppara_stat_file,pmutex ) 
							);
					}// for every single value combination
				}
				else
				{
					// NO value combination:no need to schedule
					common_path com_out_path;
					gen_common_file_path(com_out_path,str_out_prefix_common,"");
					vec_ptr_alg[i]->set_com_file_path(com_out_path);
					print_common_filelist(com_filelist,func_type,algo_type,com_out_path);
					algo_spec_output(func_type,algo_type,vec_ptr_alg[i],str_out_prefix_common,"");
					// run the algo according to specified parameter value combination
					vec_ptr_alg[i]->set_eval_func(vec_ptr_func[i]);
					vec_ptr_alg[i]->load_parameter(vec_ptr_para[i]);// Loading algorithm parameters from outer source

					vec_ptr_alg[i]->initialize();

					// progress_timer p_t;// timer of specified algorithm
					cur_task_count++;
					output_running_prompt(cur_task_count,vec_ptr_para[i]);
					pvec_stat_line.push_back(shared_ptr<stringstream>(new stringstream));// expand size by 1,use heap memory to shared the data between main thread and sub-thread 
					shared_ptr<stringstream> pcur_line=pvec_stat_line.back();
					algo_pool.schedule(
							boost::bind(thread_fun, vec_ptr_alg[i], func_type,
									algo_type, max_gen_set, has_seq_val,
									pcur_line, shared_ptr<ostream>(),
									shared_ptr<boost::mutex>()));
				}// if ( has_seq_val )
				pre_algo_type=algo_type;
			}// for every single algorithm task
		}// try
		catch(bad_cast &bc)
		{
			cout<<"bad_cast caught in batch_run:" 
				<< bc.what() << "\n";
			return -1;
		}
		catch(logic_error &le)
		{
			cout<<"logic_error caught in batch_run:" 
				<< le.what() << "\n";
			return -1;
		}
		catch(exception& e) 
		{
			cout<<"exception caught in batch_run:" 
				<<e.what()<< "\n";
			return -1;
		}
	}
	// all task are finished
	print_stat_file(pvec_stat_line);// keep run stat file output data ordered according to FIFO
	return 0;
}// end function batch_run
コード例 #25
0
ファイル: inference_utils.cpp プロジェクト: jotaraul/upgmpp
void UPGMpp::getSpanningTree( CGraph &graph, std::vector<size_t> &tree)
{
    // TODO: The efficiency of this method can be improved

    // Reset tree
    tree.clear();

    static boost::mt19937 rng;
    static bool firstExecution = true;

    if ( firstExecution )
    {
        rng.seed(time(0));
        firstExecution = false;
    }

    vector<CNodePtr> &v_nodes = graph.getNodes();
    vector<CNodePtr> v_nodesToExplore;
    map<size_t,size_t> nodesToExploreMap;
    size_t N_nodes = v_nodes.size();

    //cout << "Random: ";

    for ( size_t i_node = 0; i_node < N_nodes; i_node++ )
    {        
        boost::uniform_real<> real_generator(0,1);
        real_generator.reset();
        double rand = real_generator(rng);

        //cout << rand << " ";

        if ( rand > 0.25 )
        {
            v_nodesToExplore.push_back( v_nodes[i_node] );
            nodesToExploreMap[ v_nodes[i_node]->getID() ] =  v_nodesToExplore.size()-1;
        }

    }

    //cout << endl;

    //SHOW_VECTOR_NODES_ID("Nodes to explore: ", v_nodesToExplore)

    size_t N_nodesToExplore = v_nodesToExplore.size();

    if ( !N_nodesToExplore )
        return;

    bool nodeAdded = true;
    vector<bool> v_nodesAdded( N_nodesToExplore, false );

    //
    // Randomly select the root node
    //

    boost::uniform_int<> generator(0,N_nodesToExplore-1);
    int rand = generator(rng);

    //cout << "Root:" << rand << endl;

    v_nodesAdded[rand] = true;
    multimap<size_t, CEdgePtr> &edgesF = graph.getEdgesF();

    while ( nodeAdded )
    {
        nodeAdded = false;

        for ( size_t i_node = 0; i_node < N_nodesToExplore; i_node++ )
        {
            //cout << "Node " << i_node << " ID "<< v_nodesToExplore[i_node]->getID() << " Added? " << v_nodesAdded[i_node] << endl;

            // Check that the node has not been added to the tree yet
            if ( !v_nodesAdded[i_node] )
            {
                size_t nodeID = v_nodesToExplore[i_node]->getID();

                NEIGHBORS_IT neighbors = edgesF.equal_range(nodeID);

                for ( multimap<size_t,CEdgePtr>::iterator itNeigbhor = neighbors.first;
                      itNeigbhor != neighbors.second;
                      itNeigbhor++ )
                {

                    CEdgePtr edgePtr = (*itNeigbhor).second;
                    size_t neighborID;

                    if ( !edgePtr->getNodePosition( nodeID ) )
                        neighborID = edgePtr->getSecondNodeID();
                    else
                        neighborID = edgePtr->getFirstNodeID();

                    //cout << "Current node ID: " << nodeID << " neighbor: " << neighborID << endl;

                    if ( v_nodesAdded[nodesToExploreMap[neighborID]] )
                    {
                        v_nodesAdded[i_node] = true;
                        nodeAdded = true;
                    }
                }

            }
        }
    }

    //SHOW_VECTOR("Nodes in tree: ", v_nodesAdded)

    for ( size_t i_node = 0; i_node < v_nodesToExplore.size(); i_node++ )
    {        
        if ( v_nodesAdded[i_node] )
            tree.push_back( v_nodesToExplore[i_node]->getID() );
    }

    //SHOW_VECTOR("Tree: ", tree)
}