コード例 #1
0
ファイル: CompareTest.cpp プロジェクト: jduimovich/omr
TEST_P(Int32Compare, UsingLoadParam) {
    auto param = TRTest::to_struct(GetParam());

    char inputTrees[120] = {0};
    std::snprintf(inputTrees, 120,
       "(method return=Int32 args=[Int32, Int32] "
         "(block "
           "(ireturn "
             "(%s "
               "(iload parm=0) "
               "(iload parm=1)))))",
       param.opcode.c_str());
    auto trees = parseString(inputTrees);

    ASSERT_NOTNULL(trees);

    Tril::DefaultCompiler compiler{trees};

    ASSERT_EQ(0, compiler.compile()) << "Compilation failed unexpectedly\n" << "Input trees: " << inputTrees;

    auto entry_point = compiler.getEntryPoint<int32_t (*)(int32_t, int32_t)>();
    volatile auto exp = param.oracle(param.lhs, param.rhs);
    volatile auto act = entry_point(param.lhs, param.rhs);
    ASSERT_EQ(exp, act);
}
コード例 #2
0
ファイル: TypeConversionTest.cpp プロジェクト: jduimovich/omr
TEST_P(DoubleToFloat, UsingConst) {
    auto param = TRTest::to_struct(GetParam());

    char inputTrees[512] = {0};
    std::snprintf(inputTrees, 512,
        "(method return=Float"
        "  (block"
        "    (freturn"
        "      (d2f"
        "        (dconst %f) ) ) ) )",
        param.value);
    auto trees = parseString(inputTrees);

    ASSERT_NOTNULL(trees);

    Tril::DefaultCompiler compiler{trees};

    ASSERT_EQ(0, compiler.compile()) << "Compilation failed unexpectedly\n" << "Input trees: " << inputTrees;

    auto entry_point = compiler.getEntryPoint<float (*)()>();
    volatile auto exp = param.oracle(param.value);
    volatile auto act = entry_point();
    if (std::isnan(exp)) {
        ASSERT_EQ(std::isnan(exp), std::isnan(act));
    } else {
        ASSERT_EQ(exp, act);
    }
}
コード例 #3
0
ファイル: eval_cross_product.cpp プロジェクト: sos22/SLI
int
main(int argc, char *argv[])
{
	if (argc < 4)
		errx(1, "not enough arguments");

	init_sli();

	VexPtr<Oracle> oracle(new Oracle(NULL, NULL, NULL));

	VexPtr<StateMachine, &ir_heap> readMachine(readStateMachine(open(argv[1], O_RDONLY)));
	VexPtr<StateMachine, &ir_heap> writeMachine(readStateMachine(open(argv[2], O_RDONLY)));
	VexPtr<IRExpr, &ir_heap> assumption(readIRExpr(open(argv[3], O_RDONLY)));
	
	bool mightCrash;
	bool mightSurvive;

	evalCrossProductMachine(readMachine, writeMachine, oracle, assumption,
				AllowableOptimisations::defaultOptimisations,
				&mightSurvive, &mightCrash, ALLOW_GC);
	printf("Might survive %d, might crash %d\n",
	       mightSurvive, mightCrash);

	return 0;
}
コード例 #4
0
ファイル: TypeConversionTest.cpp プロジェクト: jduimovich/omr
TEST_P(DoubleToFloat, UsingLoadParam) {
    auto param = TRTest::to_struct(GetParam());

    char *inputTrees =
        "(method return=Float args=[Double]"
        "  (block"
        "    (freturn"
        "      (d2f"
        "        (dload parm=0) ) ) ) )";
    auto trees = parseString(inputTrees);

    ASSERT_NOTNULL(trees);

    Tril::DefaultCompiler compiler{trees};

    ASSERT_EQ(0, compiler.compile()) << "Compilation failed unexpectedly\n" << "Input trees: " << inputTrees;

    auto entry_point = compiler.getEntryPoint<float (*)(double)>();
    volatile auto exp = param.oracle(param.value);
    volatile auto act = entry_point(param.value);
    if (std::isnan(exp)) {
        ASSERT_EQ(std::isnan(exp), std::isnan(act));
    } else {
        ASSERT_EQ(exp, act);
    }
}
コード例 #5
0
ファイル: index-kgraph.cpp プロジェクト: aaalgo/donkey
        virtual void rebuild () {   // insert must not happen at this time
            if (flavor == KGRAPH_LINEAR) {
                BOOST_VERIFY(indexed_size == 0);
                return;
            }
            if (entries.size() == indexed_size) return;

            if (flavor == KGRAPH_LITE) {
                indexed_size = 0;
                delete kg_index;
                kg_index = nullptr;
                return;
            }

            KGraph *kg = nullptr;


            if (entries.size() >= min_index_size) {
                kg = KGraph::create();
                LOG(info) << "Rebuilding index for " << entries.size() << " features.";
                IndexOracle oracle(this, index_params_l1);
                kg->build(oracle, index_params, NULL);
                LOG(info) << "Swapping on new index...";
            }
            indexed_size = entries.size();
            std::swap(kg, kg_index);
            if (kg) {
                delete kg;
            }
        }
コード例 #6
0
ファイル: TypeConversionTest.cpp プロジェクト: hangshao0/omr
TEST_P(Int8ToInt32, UsingLoadParam) {
    std::string arch = omrsysinfo_get_CPU_architecture();
    SKIP_IF(OMRPORT_ARCH_S390 == arch || OMRPORT_ARCH_S390X == arch, KnownBug)
        << "The Z code generator incorrectly spills sub-integer types arguments (see issue #3525)";

    auto param = TRTest::to_struct(GetParam());

    char *inputTrees =
        "(method return=Int32 args=[Int8]"
        "  (block"
        "    (ireturn"
        "      (b2i"
        "        (bload parm=0) ) ) ) )";
    auto trees = parseString(inputTrees);

    ASSERT_NOTNULL(trees);

    Tril::DefaultCompiler compiler{trees};

    ASSERT_EQ(0, compiler.compile()) << "Compilation failed unexpectedly\n" << "Input trees: " << inputTrees;

    auto entry_point = compiler.getEntryPoint<int32_t (*)(int8_t)>();
    volatile auto exp = param.oracle(param.value);
    volatile auto act = entry_point(param.value);
    ASSERT_EQ(exp, act);
}
コード例 #7
0
ファイル: CompareTest.cpp プロジェクト: jduimovich/omr
TEST_P(DoubleCompare, UsingConst) {
    auto param = TRTest::to_struct(GetParam());

    char inputTrees[1024] = {0};
    std::snprintf(inputTrees, 1024,
       "(method return=Int32 "
         "(block "
           "(ireturn "
             "(%s "
               "(dconst %f) "
               "(dconst %f)))))",
       param.opcode.c_str(), param.lhs, param.rhs);
    auto trees = parseString(inputTrees);

    ASSERT_NOTNULL(trees);

    Tril::DefaultCompiler compiler{trees};

    ASSERT_EQ(0, compiler.compile()) << "Compilation failed unexpectedly\n" << "Input trees: " << inputTrees;

    auto entry_point = compiler.getEntryPoint<int32_t (*)(void)>();
    volatile auto exp = param.oracle(param.lhs, param.rhs);
    volatile auto act = entry_point();
    ASSERT_EQ(exp, act);
}
コード例 #8
0
int main() 
{
	int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, 
	       sea_hag, tribute, smithy};

	int i, n, players, player, handCount, deckCount, seed;
	  //struct gameState state;
	struct gameState state;

	player = 0;
	n = 0;
	srand(time(NULL));

	printf("Running Random Adventurer Test\n");

	  /*
										--- Author's Note ---
	  So, I had problems running out of memory when I used the same gameState variable more than 12 times, and
	  I honestly don't know why. I momentarily solved this problem by adding more for loops and creating more gamestates;
	  I was still able to get decent coverage, though not up to the amount of tests I originally had in mind.

	  */

	for (i = 0; i < MAX_TESTS; i++) 
	{

		players = rand() % 3 + 2;
		seed = rand();		//pick random seed
		initializeGame(players, k, seed, &state);	//initialize Gamestate 

	  //Initiate valid state variables
		state.deckCount[player] = rand() % 20; //Pick random deck size out of MAX DECK size
		state.discardCount[player] = rand() % 20;
		handCount = rand() % 10;

		state.hand[0][0] = adventurer;

		  //Copy state variables
		deckCount = state.deckCount[player];

		  //1 in 3 chance of making empty deck for coverage
		if (seed % 3 == 0) 
		{
			state.deckCount[player] = 0;
		}
	
		printf("Test: %d\n", i);
	
		oracle(state, deckCount, state.discardCount[0]);		//Run adventurer card

	
	}
	 
	printf("Tests Complete\n");

	return 0;
}
コード例 #9
0
ファイル: DynamicOracleTest.cpp プロジェクト: majineu/Parser
int ComputeLinearTreeLoss(const CState & state,
                          const vector<CDepTree *> & nodes,
                          const CIDMap::ACTION_TYPE action) {
  CDynamicOracleSearcher oracle(state, nodes);
  oracle.InitStackCosts();
  oracle.BuildStacks(action);
  oracle.ComputeStackCost(action);
  return oracle.LossLinearTree();
}
コード例 #10
0
ファイル: DynamicOracleTest.cpp プロジェクト: majineu/Parser
int BestAction(const CState & state, const vector<CDepTree*> & nodes) {
  set<CIDMap::ACTION_TYPE> actions;
  CDynamicOracleSearcher oracle(state, nodes);
  oracle.InitStackCosts();
//  oracle.Oracle(0, &actions);
  oracle.Oracle(&actions);
  vector<double> scores(CIDMap::GetOutcomeNum(), 0.);
  return oracle.BestAction(actions, scores);
}
コード例 #11
0
ファイル: mcp56.c プロジェクト: ctz/cryptopals
int main(int argc, char **argv)
{
  pool p[1] = { pool_create() };  
  random_init();

  /* biases at 16 and 32, so we prefix our 30 byte secret with
   * two bytes to start with, up to 17 */
  byteblock prefix = { (uint8_t *) "AAAAAAAAAAAAAAAAAA", 2 };
  
  assert(argc == 2);
  byteblock secret = from_base64(p, argv[1]);
  
  assert(secret.len == SECRET_LEN);
  
  unsigned counts[SECRET_LEN][256];
  memset(counts, 0, sizeof(counts));
  
  while (prefix.len < 18)
  {
    uint8_t buf[64];
    byteblock bb = { buf, 0 };
    
    for (size_t i = 0; i < ROUNDS; i++)
    {
      oracle(&prefix, &secret, &bb);
      
      if (prefix.len <= 15)
      {
        /* bias at 16 towards 240 (full) 0 (half) 16 (half) */
        uint8_t b16 = buf[15];
        counts[15 - prefix.len][b16 ^ 240] += FULL_WEIGHT;
        counts[15 - prefix.len][b16 ^ 0] += HALF_WEIGHT;
        counts[15 - prefix.len][b16 ^ 16] += HALF_WEIGHT;
      }
        
      /* bias at 32 towards 224 (full) 0 (half) 32 (half) */
      uint8_t b32 = buf[31];
      counts[31 - prefix.len][b32 ^ 224] += FULL_WEIGHT;
      counts[31 - prefix.len][b32 ^ 0] += HALF_WEIGHT;
      counts[31 - prefix.len][b32 ^ 32] += HALF_WEIGHT;
    }
    
    prefix.len++;
    
    byteblock plaintext = recover(p, counts);
    printf("guess: %s\n", to_ascii(p, &plaintext));
  }
  
  byteblock recovered = recover(p, counts);
  printf("message: %s\n", to_ascii(p, &recovered));
  
  p->finish(p);
  return 0;
}
コード例 #12
0
ファイル: refactor_runner.cpp プロジェクト: diffblue/cbmc
int run_refactor(optionst &options, messaget::mstreamt &result,
                 const symbol_tablet &st, const goto_functionst &gf)
{
    refactor_preprocessingt preproc(options, st, gf);
    refactor_symex_learnt learn_cfg(preproc.get_program());
    refactor_symex_verifyt verify_cfg(preproc.get_program());
    cegis_symex_learnt<refactor_preprocessingt, refactor_symex_learnt> learn(
        options, preproc, learn_cfg);
    cegis_symex_verifyt<refactor_symex_verifyt> oracle(options, verify_cfg);
    return run_cegis_with_statistics_wrapper(
               result, options, learn, oracle, preproc);
}
コード例 #13
0
int main() {

	int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, 
	       sea_hag, tribute, smithy};
	
	int i, n, players, player, handCount, deckCount, seed;
	  //struct gameState state;
	struct gameState state;

	srand(time(NULL));
	player = 0;
	n = 1;

	printf("Running Random Card Test for Village\n");

	for (i = 0; i < MAX_TESTS; i++) 
	{
	  
		players = rand() % 3 + 2;
		seed = rand();		//pick random seed
		
		initializeGame(players, k, seed, &state);	//initialize Gamestate

		 //Initiate valid state variables
		state.deckCount[player] = rand() % MAX_DECK; //Pick random deck size out of MAX DECK size
		state.discardCount[player] = rand() % MAX_DECK;
		handCount = rand() % MAX_HAND;	

		
		state.hand[0][0] = village;
		
		 //Copy state variables
		
		deckCount = state.deckCount[player];

		printf("test: %d\n", n);

		oracle(state, state.handCount[0], state.discardCount[0], state.numActions);		//Run adventurer card

		n++;
	}

	printf("Tests Complete\n");

	return 0;
}
コード例 #14
0
ファイル: index-kgraph.cpp プロジェクト: donkey-fart/donkey
 virtual void rebuild () {   // insert must not happen at this time
     if (linear) {
         indexed_size = entries.size();
         return;
     }
     if (entries.size() == indexed_size) return;
     KGraph *kg = nullptr;
     if (entries.size() >= min_index_size) {
         kg = KGraph::create();
         LOG(info) << "Rebuilding index for " << entries.size() << " features.";
         IndexOracle oracle(this);
         kg->build(oracle, index_params, NULL);
         LOG(info) << "Swapping on new index...";
     }
     indexed_size = entries.size();
     std::swap(kg, kg_index);
     if (kg) {
         delete kg;
     }
 }
コード例 #15
0
ファイル: TypeConversionTest.cpp プロジェクト: jduimovich/omr
TEST_P(FloatToInt32, UsingLoadParam) {
    auto param = TRTest::to_struct(GetParam());

    char *inputTrees =
        "(method return=Int32 args=[Float]"
        "  (block"
        "    (ireturn"
        "      (f2i"
        "        (fload parm=0) ) ) ) )";
    auto trees = parseString(inputTrees);

    ASSERT_NOTNULL(trees);

    Tril::DefaultCompiler compiler{trees};

    ASSERT_EQ(0, compiler.compile()) << "Compilation failed unexpectedly\n" << "Input trees: " << inputTrees;

    auto entry_point = compiler.getEntryPoint<int32_t (*)(float)>();
    volatile auto exp = param.oracle(param.value);
    volatile auto act = entry_point(param.value);
    ASSERT_EQ(exp, act);
}
コード例 #16
0
ファイル: dotp.c プロジェクト: cycomachead/61c
int main() {
  // Generate input vectors
  double *x = gen_array(ARRAY_SIZE);
  double *y = gen_array(ARRAY_SIZE);
  double result, answer;
  answer = oracle(x, y);
  // Test framework that sweeps the number of threads and times each ru
  double start_time, run_time;
  int num_threads = omp_get_max_threads();
  for(int i=1; i<=num_threads; i++) {
    omp_set_num_threads(i);
    start_time = omp_get_wtime();
    for(int j=0; j<REPEAT; j++) {
      result = dotp(x,y);
      if (result != answer) {
        printf("Incorrect dotp %f %f\n", result, answer);
        return 0;
      }
    }
    run_time = omp_get_wtime() - start_time;
    printf(" %d thread(s) took %f seconds\n",i,run_time);
  }
}
コード例 #17
0
ファイル: TypeConversionTest.cpp プロジェクト: jduimovich/omr
TEST_P(FloatToInt64, UsingConst) {
    auto param = TRTest::to_struct(GetParam());

    char inputTrees[160] = {0};
    std::snprintf(inputTrees, 160,
        "(method return=Int64"
        "  (block"
        "    (lreturn"
        "      (f2l"
        "        (fconst %f) ) ) ) )",
        param.value);
    auto trees = parseString(inputTrees);

    ASSERT_NOTNULL(trees);

    Tril::DefaultCompiler compiler{trees};

    ASSERT_EQ(0, compiler.compile()) << "Compilation failed unexpectedly\n" << "Input trees: " << inputTrees;

    auto entry_point = compiler.getEntryPoint<int64_t (*)()>();
    volatile auto exp = param.oracle(param.value);
    volatile auto act = entry_point();
    ASSERT_EQ(exp, act);
}
コード例 #18
0
ファイル: train.cpp プロジェクト: jni/candidate_mc
int main(int argc, char** argv) {

	try {

		util::ProgramOptions::init(argc, argv);
		logger::LogManager::init();

		Hdf5CragStore   cragStore(optionProjectFile.as<std::string>());
		Hdf5VolumeStore volumeStore(optionProjectFile.as<std::string>());

		Crag crag;
		cragStore.retrieveCrag(crag);

		NodeFeatures nodeFeatures(crag);
		EdgeFeatures edgeFeatures(crag);

		LOG_USER(logger::out) << "reading features" << std::endl;
		cragStore.retrieveNodeFeatures(crag, nodeFeatures);
		cragStore.retrieveEdgeFeatures(crag, edgeFeatures);

		BundleOptimizer::Parameters parameters;
		parameters.lambda      = optionRegularizerWeight;
		parameters.epsStrategy = BundleOptimizer::EpsFromGap;
		BundleOptimizer optimizer(parameters);

		BestEffort*  bestEffort  = 0;
		OverlapLoss* overlapLoss = 0;

		if (optionBestEffortFromProjectFile) {

			LOG_USER(logger::out) << "reading best-effort" << std::endl;

			bestEffort = new BestEffort(crag);

			vigra::HDF5File project(
					optionProjectFile.as<std::string>(),
					vigra::HDF5File::OpenMode::ReadWrite);
			project.cd("best_effort");
			vigra::ArrayVector<int> beNodes;
			vigra::MultiArray<2, int> beEdges;
			project.readAndResize("nodes", beNodes);
			project.readAndResize("edges", beEdges);

			std::set<int> nodes;
			for (int n : beNodes)
				nodes.insert(n);

			std::set<std::pair<int, int>> edges;
			for (int i = 0; i < beEdges.shape(1); i++)
				edges.insert(
						std::make_pair(
							std::min(beEdges(i, 0), beEdges(i, 1)),
							std::max(beEdges(i, 0), beEdges(i, 1))));

			for (Crag::NodeIt n(crag); n != lemon::INVALID; ++n)
				bestEffort->node[n] = nodes.count(crag.id(n));

			for (Crag::EdgeIt e(crag); e != lemon::INVALID; ++e)
				bestEffort->edge[e] = edges.count(
						std::make_pair(
								std::min(crag.id(crag.u(e)), crag.id(crag.v(e))),
								std::max(crag.id(crag.u(e)), crag.id(crag.v(e)))));

		} else {

			LOG_USER(logger::out) << "reading ground-truth" << std::endl;
			ExplicitVolume<int> groundTruth;
			volumeStore.retrieveGroundTruth(groundTruth);

			LOG_USER(logger::out) << "finding best-effort solution" << std::endl;
			overlapLoss = new OverlapLoss(crag, groundTruth);
			bestEffort = new BestEffort(crag, *overlapLoss);
		}

		Loss* loss = 0;
		bool  destructLoss = false;

		if (optionLoss.as<std::string>() == "hamming") {

			LOG_USER(logger::out) << "using Hamming loss" << std::endl;

			loss = new HammingLoss(crag, *bestEffort);
			destructLoss = true;

		} else if (optionLoss.as<std::string>() == "overlap") {

			LOG_USER(logger::out) << "using overlap loss" << std::endl;

			if (!overlapLoss) {

				LOG_USER(logger::out) << "reading ground-truth" << std::endl;
				ExplicitVolume<int> groundTruth;
				volumeStore.retrieveGroundTruth(groundTruth);

				LOG_USER(logger::out) << "finding best-effort solution" << std::endl;
				overlapLoss = new OverlapLoss(crag, groundTruth);
			}

			loss = overlapLoss;

		} else {

			LOG_ERROR(logger::out)
					<< "unknown loss: "
					<< optionLoss.as<std::string>()
					<< std::endl;
			return 1;
		}

		if (optionNormalizeLoss) {

			LOG_USER(logger::out) << "normalizing loss..." << std::endl;
			loss->normalize(crag, MultiCut::Parameters());
		}

		Oracle oracle(
				crag,
				nodeFeatures,
				edgeFeatures,
				*loss,
				*bestEffort);

		std::vector<double> weights(nodeFeatures.dims() + edgeFeatures.dims(), 0);
		optimizer.optimize(oracle, weights);

		storeVector(weights, optionFeatureWeights);

		if (destructLoss && loss != 0)
			delete loss;

		if (overlapLoss)
			delete overlapLoss;

		if (bestEffort)
			delete bestEffort;

	} catch (boost::exception& e) {

		handleException(e, std::cerr);
	}
}
int main(int argc, const char ** argv) {
	auto start = std::chrono::high_resolution_clock::now();

	std::cout << "MSAcquisitionSimulator Version " << MSAcquisitionSimulator_VERSION_MAJOR << "." << MSAcquisitionSimulator_VERSION_MINOR << "." << MSAcquisitionSimulator_VERSION_PATCH << std::endl;
	std::cout << "AcquisitionSimulator Version " << AcquisitionSimulator_VERSION_MAJOR << "." << AcquisitionSimulator_VERSION_MINOR << "." << AcquisitionSimulator_VERSION_PATCH << std::endl;

	std::string sqlite_in_path;
	std::string mzml_out_path;
	std::string param_file_path;
	std::string fido_out_path;
	std::string fasta_in_path;
	std::string target_decoy_out_path;
	std::string acquisition_algorithm_name;

	std::vector<std::string> acquisition_param_values;

	double ms1_scan_time;
	double ms2_scan_time;
	double scan_overhead_time;
	int acquisition_length;

	double elution_tau;
	double elution_sigma;

	double resolution;
	double dynamic_range;

	double db_search_min_mass;
	double db_search_max_mass;
	double db_search_mass_tolerance;
	int db_search_max_missed_cleavages;
	int db_search_max_dynamic_mods;
	int db_search_min_enzymatic_termini;
	double null_lambda;

	double max_ms1_injection_time;
	double max_ms2_injection_time;
	double ms1_target_total_ion_count;
	double ms2_target_total_ion_count;

	std::vector<DBPTM> PTMs;
	std::vector<DBEnzyme> enzymes;


	//region Command line specification
	boost::program_options::options_description general("USAGE: AcquisitionSimulator [options] ground_truth.tab\n\nOptions");
	general.add_options()
			("help", "Print usage and exit.")
			("conf,c", boost::program_options::value<std::string>(&param_file_path)->default_value("acquisition.conf"), "Input path to config file.")
			("mzml_out_path,o", boost::program_options::value<std::string>(&mzml_out_path)->default_value("sample.mzML"), "output path for mzML file.")
			("fido_out_path,f", boost::program_options::value<std::string>(&fido_out_path)->default_value("sample.fido"), "output path for fido file.")
			("target_decoy_out_path,d", boost::program_options::value<std::string>(&target_decoy_out_path)->default_value("targetDecoy.txt"), "output path for fido targetDecoy file.")
			;

	boost::program_options::options_description hidden("");
	hidden.add_options()
			("ground_truth_in_path", boost::program_options::value<std::string>(&sqlite_in_path), "input path for ground truth file made by GroundTruthSimulator.")
			;

	boost::program_options::options_description all("Allowed options");
	all.add(general).add(hidden);

	boost::program_options::positional_options_description p;
	p.add("ground_truth_in_path", -1);

	boost::program_options::variables_map vm;
	boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(all).positional(p).run(), vm);
	boost::program_options::notify(vm);
	//endregion

	//region Command line processing
	if (vm.count("help")) {
		std::cout << general << std::endl;
		return 0;
	}

	//region config file specification
	boost::program_options::options_description config("Configuration file options");
	config.add_options()
			("acquisition_algorithm", boost::program_options::value<std::string>(&acquisition_algorithm_name)->default_value("TopN"), "acquisition algorithm")
			("acquisition_algorithm_params", boost::program_options::value<std::vector<std::string>>(&acquisition_param_values)->multitoken(), "acquisition_algorithm_params")
			("ms1_scan_time", boost::program_options::value<double>(&ms1_scan_time)->default_value(0.256), "ms1_scan_time")
			("ms2_scan_time", boost::program_options::value<double>(&ms2_scan_time)->default_value(0.064), "ms2_scan_time")
			("scan_overhead_time", boost::program_options::value<double>(&scan_overhead_time)->default_value(0.015), "scan_overhead_time")
			("acquisition_length", boost::program_options::value<int>(&acquisition_length)->default_value(3600), "acquisition_length")
			("fasta", boost::program_options::value<std::string>(&fasta_in_path), "acquisition fasta_in_path")
			("elution_tau", boost::program_options::value<double>(&elution_tau)->default_value(4), "elution_tau")
			("elution_sigma", boost::program_options::value<double>(&elution_sigma)->default_value(6), "elution_sigma")
			("resolution", boost::program_options::value<double>(&resolution)->default_value(60000), "resolution")
			("dynamic_range", boost::program_options::value<double>(&dynamic_range)->default_value(5000), "dynamic_range")
			("db_search_min_mass", boost::program_options::value<double>(&db_search_min_mass)->default_value(200), "db_search_min_mass")
			("db_search_max_mass", boost::program_options::value<double>(&db_search_max_mass)->default_value(9000), "db_search_max_mass")
			("db_search_max_missed_cleavages", boost::program_options::value<int>(&db_search_max_missed_cleavages)->default_value(0), "db_search_max_missed_cleavages")
			("db_search_max_dynamic_mods", boost::program_options::value<int>(&db_search_max_dynamic_mods)->default_value(0), "db_search_max_dynamic_mods")
			("db_search_min_enzymatic_termini", boost::program_options::value<int>(&db_search_min_enzymatic_termini)->default_value(2), "db_search_min_enzymatic_termini")
			("db_search_mass_tolerance", boost::program_options::value<double>(&db_search_mass_tolerance)->default_value(.05), "db_search_mass_tolerance")
			("db_search_PTM", boost::program_options::value<std::vector<DBPTM> >(&PTMs)->multitoken(), "PTMs")
			("db_search_enzyme", boost::program_options::value<std::vector<DBEnzyme>>(&enzymes)->multitoken(), "enzymes")
			("db_search_null_lambda", boost::program_options::value<double>(&null_lambda)->default_value(6), "db_search_null_lambda")
			("max_ms1_injection_time", boost::program_options::value<double>(&max_ms1_injection_time)->default_value(0.2), "max_ms1_injection_time")
			("max_ms2_injection_time", boost::program_options::value<double>(&max_ms2_injection_time)->default_value(0.5), "max_ms2_injection_time")
			("ms1_target_total_ion_count", boost::program_options::value<double>(&ms1_target_total_ion_count)->default_value(1e6), "ms1_target_total_ion_count")
			("ms2_target_total_ion_count", boost::program_options::value<double>(&ms2_target_total_ion_count)->default_value(1e5), "ms2_target_total_ion_count")
			;
	boost::program_options::variables_map vm_config;
	std::ifstream config_file(param_file_path.c_str());

	if(!config_file.is_open()) {
		std::cerr << "Unable to open configuration file: " << param_file_path << std::endl;
		exit(1);
	}

	boost::program_options::store(boost::program_options::parse_config_file(config_file, config, true), vm_config);
	boost::program_options::notify(vm_config);
	//endregion


	ElutionShapeSimulator elution_shape_simulator(elution_tau, elution_sigma);
	std::unique_ptr<GroundTruthText> db = std::unique_ptr<GroundTruthText>(new GroundTruthText(sqlite_in_path, false));
	std::unique_ptr<Instrument> instrument = std::unique_ptr<Instrument>(new Instrument(resolution, dynamic_range, ms1_scan_time, ms2_scan_time,
																						scan_overhead_time, max_ms1_injection_time,
																						max_ms2_injection_time, ms1_target_total_ion_count,
																						ms2_target_total_ion_count));

	Sequencer sequencer(fasta_in_path, PTMs, enzymes, db_search_mass_tolerance, db_search_max_missed_cleavages, db_search_min_enzymatic_termini, db_search_min_mass, db_search_max_mass, db_search_max_dynamic_mods, null_lambda);
	Oracle oracle(db.get(), instrument.get(), elution_shape_simulator);
	MzMLWriter mzml_writer(mzml_out_path);
	FidoWriter fido_writer(fido_out_path);

	AcquisitionController* controller = get_controller(acquisition_algorithm_name, acquisition_param_values);

	int ms1_count = 0;
	int ms2_count = 0;
	int quality_ms2_count = 0;
	double current_time = 0;

	std::cout << "Simulating Acquisition:" << std::endl;

	while (current_time <= acquisition_length) {
		std::unique_ptr<ScanRequest> scan_request = controller->get_scan_request(current_time);
		std::unique_ptr<Scan> scan = oracle.get_scan_data(scan_request.get(), current_time);

		if (scan->scan_type == Scan::ScanType::MS2) {
			ms2_count++;
			MS2Scan* tmp_scan = static_cast<MS2Scan*>(scan.get());
			sequencer.sequence_ms2_scan(tmp_scan);

			if (tmp_scan->probability >= 0 && tmp_scan->peptide != "DECOY") {
				fido_writer.write_peptide(tmp_scan->probability, tmp_scan->peptide, tmp_scan->proteins);
				if (tmp_scan->probability >= .9) quality_ms2_count++;
			}

			/*double max_int = 0;
			std::string max_pep;
			for (auto itr = tmp_scan->peptide2intensity.begin(); itr != tmp_scan->peptide2intensity.end(); ++itr) {
				if (itr->second > max_int) {
					max_int = itr->second;
					max_pep = itr->first;
				}
			}
			std::cout << tmp_scan->precursor_peak.mz << " " << tmp_scan->precursor_peak.intensity << " " << tmp_scan->elapsed_time << " " << tmp_scan->TIC << " " << max_pep << " " << max_int / tmp_scan->TIC << " " << tmp_scan->peptide << std::endl;
			*/
		} else {
			ms1_count++;
		}

		controller->process_scan(scan.get());
		current_time += scan->elapsed_time;

		if (scan->scan_id % 20 == 0) {
			std::cout << "\rCurrent time: " << current_time << " seconds. MS1 count: " << ms1_count << ". MS2 count: " << ms2_count << ". Num PSMs >= 0.9: " << quality_ms2_count << std::flush;
		}

		mzml_writer.add_to_scan_buffer(std::move(scan));
		if (mzml_writer.buffer.size() > 100) mzml_writer.write_buffer();
	}

	std::cout << "\rCurrent time: " << current_time << " seconds. MS1 count: " << ms1_count << ". MS2 count: " << ms2_count << ". Num PSMs >= 0.9: " << quality_ms2_count << std::endl;

	mzml_writer.write_buffer();
	mzml_writer.output_file_end();

	mzml_writer.close_file();
	fido_writer.close_file();

	sequencer.write_target_decoy_file(target_decoy_out_path);

	auto end = std::chrono::high_resolution_clock::now();

	std::cout << "Simulation Complete." << std::endl;
	std::cout << "Elapsed time: " << std::chrono::duration_cast<std::chrono::seconds>(end-start).count() << " seconds" << std::endl;

	return 0;
}
コード例 #20
0
int main(int argc, char * argv[])
{
  srand(time(NULL));

  // Let us define a 3 layer perceptron architecture
  auto input = gaml::mlp::input<X>(INPUT_DIM, fillInput);
  auto l1 = gaml::mlp::layer(input, HIDDEN_LAYER_SIZE, gaml::mlp::mlp_sigmoid(), gaml::mlp::mlp_dsigmoid());
  auto l2 = gaml::mlp::layer(l1, HIDDEN_LAYER_SIZE, gaml::mlp::mlp_sigmoid(), gaml::mlp::mlp_dsigmoid());
  auto output = gaml::mlp::layer(l2, OUTPUT_DIM, gaml::mlp::mlp_identity(), gaml::mlp::mlp_didentity());
  auto mlp = gaml::mlp::perceptron(output, output_of);

  // Create a training base
  // Let us try to fit a noisy sinc function
  Basis basis;
  basis.resize(NB_SAMPLES);
  for(auto& d: basis)
    {
      d.first = {{ -10.0 + 20.0 * gaml::random::uniform(0.0, 1.0) }} ;
      d.second = noisy_oracle(d.first);
    }

  // Set up the parameters for learning the MLP with a gradient descent
  gaml::mlp::learner::gradient::parameter gradient_params;
  gradient_params.alpha = 1e-2;
  gradient_params.dalpha = 1e-3;

  gradient_params.verbose = true;
  // The stopping criteria
  gradient_params.max_iter = 10000;
  gradient_params.min_dparams = 1e-7;

  // Create the learner
  auto learning_algorithm = gaml::mlp::learner::gradient::algorithm(mlp, gradient_params, gaml::mlp::loss::Quadratic(), fillOutput);

  // Call the learner on the basis and get the learned predictor
  auto predictor = learning_algorithm(basis.begin(),
				      basis.end(),
				      input_of_data,
				      output_of_data);

  // Print out the structure of the perceptron we learned
  std::cout << predictor << std::endl;

  // Dump the results
  std::ofstream outfile("example-005-samples.data");
  for(auto& b: basis)
    outfile << b.first[0] << " "
	    << b.second[0] << " " 
	    << std::endl;
  outfile.close();

  outfile.open("example-005-regression.data");
  X x;
  for(x[0] = -10; x[0] < 10 ; x[0] += 0.1)
    {
      auto output = predictor(x);
      outfile << x[0]         << " "
	      << oracle(x)[0] << " "
	      << output[0]    << std::endl;
    }
  outfile.close();

  std::cout << "You can plot the results using gnuplot :" << std::endl;
  std::cout << "gnuplot " << ML_MLP_SHAREDIR << "/plot-example-005.gplot" << std::endl;
  std::cout << "This will produce example-005.ps" << std::endl;


  // Let us compute the empirical risk.
  auto evaluator = gaml::risk::empirical(gaml::mlp::loss::Quadratic());
  double risk = evaluator(predictor,
			  basis.begin(),
			  basis.end(),
			  input_of_data,
			  output_of_data);
  std::cout << "Empirical risk = " << risk << std::endl;

  // We will use a 6-fold cross-validation to estimate the real risk.
  auto kfold_evaluator = gaml::risk::cross_validation(gaml::mlp::loss::Quadratic(),
						      gaml::partition::kfold(6),
						      true);

  double kfold_risk = kfold_evaluator(learning_algorithm,
				      basis.begin(),basis.end(),
				      input_of_data,output_of_data);

  std::cout << "Estimation of the real risk (6-fold): "
	    << kfold_risk << std::endl;


}
コード例 #21
0
Y noisy_oracle(X x)
{
  Y y = oracle(x);
  y[0] += gaml::random::uniform(-0.1, 0.1);
  return y;
}
コード例 #22
0
Pairing * PairGeneratorSector::run(HitCollection & hits, const GeometrySupplement & geomSupplement,
				uint nThreads, const TripletConfigurations & layerTriplets, const Grid & grid)
		{

	std::vector<uint> oracleOffset;
	uint totalMaxPairs = 0;

	uint nLayerTriplets = layerTriplets.size();
	for(uint e = 0; e < grid.config.nEvents; ++e){
		for(uint p = 0; p < nLayerTriplets; ++p){

			TripletConfiguration layerPair(layerTriplets, p);

			LayerGrid layer1(grid, layerPair.layer1(),e);
			LayerGrid layer2(grid, layerPair.layer2(),e);

			uint nMaxPairs = layer1.size()*layer2.size();
			nMaxPairs = 32 * std::ceil(nMaxPairs / 32.0); //round to next multiple of 32

			oracleOffset.push_back(totalMaxPairs);
			totalMaxPairs += nMaxPairs;
		}
	}

	LOG << "Initializing oracle offsets for pair gen...";
	clever::vector<uint, 1> m_oracleOffset(oracleOffset, ctx);
	LOG << "done[" << m_oracleOffset.get_count()  << "]" << std::endl;

	LOG << "Initializing oracle for pair gen...";
	clever::vector<uint, 1> m_oracle(0, std::ceil(totalMaxPairs / 32.0), ctx);
	LOG << "done[" << m_oracle.get_count()  << "]" << std::endl;

	LOG << "Initializing prefix sum for pair gen...";
	clever::vector<uint, 1> m_prefixSum(0, grid.config.nEvents*nLayerTriplets*nThreads+1, ctx);
	LOG << "done[" << m_prefixSum.get_count()  << "]" << std::endl;

	//ctx.select_profile_event(KERNEL_COMPUTE_EVT());

	LOG << "Running pair gen kernel...";
	cl_event evt = pairCount.run(
			//configuration
			layerTriplets.transfer.buffer(Layer1()), layerTriplets.transfer.buffer(Layer2()), grid.config.nLayers,
			grid.transfer.buffer(Boundary()),
			grid.config.MIN_Z, grid.config.sectorSizeZ(),	grid.config.nSectorsZ,
			grid.config.MIN_PHI, grid.config.sectorSizePhi(), grid.config.nSectorsPhi,
			layerTriplets.transfer.buffer(pairSpreadZ()), layerTriplets.transfer.buffer(pairSpreadPhi()),
			// hit input
			hits.transfer.buffer(GlobalX()), hits.transfer.buffer(GlobalY()), hits.transfer.buffer(GlobalZ()),
			// intermeditate data: oracle for hit pairs, prefix sum for found pairs
			m_oracle.get_mem(), m_oracleOffset.get_mem(), m_prefixSum.get_mem(),
			//local
			local_param(sizeof(cl_uint), (grid.config.nSectorsZ+1)*(grid.config.nSectorsPhi+1)),
			//thread config
			range(nThreads, nLayerTriplets, grid.config.nEvents),
			range(nThreads, 1,1));
	PairGeneratorSector::events.push_back(evt);
	LOG << "done" << std::endl;

	if(PROLIX){
		PLOG << "Fetching prefix sum for pair gen...";
		std::vector<uint> vPrefixSum(m_prefixSum.get_count());
		transfer::download(m_prefixSum,vPrefixSum,ctx);
		PLOG << "done" << std::endl;

		PLOG << "Prefix sum: ";
		for(auto i : vPrefixSum){
			PLOG << i << " ; ";
		}
		PLOG << std::endl;
	}


	if(PROLIX){
		PLOG << "Fetching oracle for pair gen...";
		std::vector<uint> oracle(m_oracle.get_count());
		transfer::download(m_oracle,oracle,ctx);
		PLOG << "done" << std::endl;

		PLOG << "Oracle: ";
		for(auto i : oracle){
			PLOG << i << " ; ";
		}
		PLOG << std::endl;
	}

	//Calculate prefix sum
	PrefixSum prefixSum(ctx);
	evt = prefixSum.run(m_prefixSum.get_mem(), m_prefixSum.get_count(), nThreads, PairGeneratorSector::events);
	uint nFoundPairs;
	transfer::downloadScalar(m_prefixSum, nFoundPairs, ctx, true, m_prefixSum.get_count()-1, 1, &evt);

	if(PROLIX){
		PLOG << "Fetching prefix sum for pair gen...";
		std::vector<uint> vPrefixSum(m_prefixSum.get_count());
		transfer::download(m_prefixSum,vPrefixSum,ctx);
		PLOG << "done" << std::endl;

		PLOG << "Prefix sum: ";
		for(auto i : vPrefixSum){
			PLOG << i << " ; ";
		}
		PLOG << std::endl;
	}

	LOG << "Initializing pairs...";
	Pairing * hitPairs = new Pairing(ctx, nFoundPairs, grid.config.nEvents, layerTriplets.size());
	LOG << "done[" << hitPairs->pairing.get_count()  << "]" << std::endl;


	LOG << "Running pair gen store kernel...";
	evt = pairStore.run(
			//configuration
			layerTriplets.transfer.buffer(Layer1()), layerTriplets.transfer.buffer(Layer2()), grid.config.nLayers,
			//grid
			grid.transfer.buffer(Boundary()), grid.config.nSectorsZ, grid.config.nSectorsPhi,
			// input for oracle and prefix sum
			m_oracle.get_mem(), m_oracleOffset.get_mem(), m_prefixSum.get_mem(),
			// output of pairs
			hitPairs->pairing.get_mem(), hitPairs->pairingOffsets.get_mem(),
			//thread config
			range(nThreads, nLayerTriplets, grid.config.nEvents),
			range(nThreads, 1,1));
	PairGeneratorSector::events.push_back(evt);
	LOG << "done" << std::endl;

	if(PROLIX){
		PLOG << "Fetching pairs...";
		std::vector<uint2> pairs = hitPairs->getPairings();
		PLOG <<"done[" << pairs.size() << "]" << std::endl;

		PLOG << "Pairs:" << std::endl;
		for(uint i = 0; i < nFoundPairs; ++i){
			PLOG << "[" << i << "] "  << pairs[i].x << "-" << pairs[i].y << std::endl;
		}

		PLOG << "Fetching pair offets...";
		std::vector<uint> pairOffsets = hitPairs->getPairingOffsets();
		PLOG <<"done[" << pairOffsets.size() << "]" << std::endl;

		PLOG << "Pair Offsets:" << std::endl;
		for(uint i = 0; i < pairOffsets.size(); ++i){
			PLOG << "[" << i << "] "  << pairOffsets[i] << std::endl;
		}
	}

	return hitPairs;
}
コード例 #23
0
ファイル: util.cpp プロジェクト: ultimatepp/mirror
SqlVal GetYearDayIndex(const SqlVal& date)
{
    SqlVal mssql("substring(convert(varchar(max), " + ~date + ", 1), 1, 5)", SqlS::FN);
    SqlVal oracle(SqlFunc("to_char", date, "MM/DD"));
    return SqlVal(SqlCode(MSSQL, ~mssql)(~oracle), SqlS::FN);
}
コード例 #24
0
ファイル: fonctionsBoucles.cpp プロジェクト: LogicalKip/CUR
void calculerRound(int nRound, int pv, int pvEnnemis, int pillz, int pillzEnnemis, bool determinQuiEstTeste, int carteEnnemieEnvoyee, int dernierRoundACalculer) {
    int pillzRestants, pillzEnnemisRestants;
    bool jeGagne = false;
    
    if (nRound == 5 || pvEnnemis <= 0 || pv <= 0) { // Combat terminé 
        if (pv <= 0 && pvEnnemis <= 0)
            rajouterEgalites();
        else if (pv > pvEnnemis)
            rajouterVictoires();
        else if (pv < pvEnnemis)
            rajouterDefaites();
        else
            rajouterEgalites();
    }
    else {
        if (nRound == dernierRoundACalculer+1) {
            if (furyUtilisee) {
                carteAlliee[persoTest].guessedScoreFury[pillzTest]  += oracle(pv, pillz, pvEnnemis, pillzEnnemis);
            } else {
                carteAlliee[persoTest].guessedScore[pillzTest]      += oracle(pv, pillz, pvEnnemis, pillzEnnemis);
            }
            
            return;
        }
        
        for (int i = 0 ; i < 4 ; i++) { // Pour chaque carte alliée
            if (!carteAlliee[i].supposeeUtilisee && !carteAlliee[i].utiliseeACoupSur) { // ne continuer que si elle n'est pas supposée utilisée, ni pour de bon
                if (determinQuiEstTeste)
                    persoTest = i;
                carteAlliee[i].supposeeUtilisee = true; // la supposer utilisée
                for (int j = 0 ; j < 4 ; j++) { // Pour chaque carte ennemie
                    if (!carteEnnemie[j].supposeeUtilisee && !carteEnnemie[j].utiliseeACoupSur) { // ne continuer que si elle n'est pas supposée utilisée, ni pour de bon
                        if (!(determinQuiEstTeste && carteEnnemieEnvoyee >= 0 && carteEnnemieEnvoyee <= 3) || j == carteEnnemieEnvoyee) { // En simplifiant par la logique, on obtient ça
                        //TODO vérifier la condition, elle est bizarre, et mettre un commentaire qui résume mieux celle-ci. De plus, "compris entre 0 et 3", ça veut dire "différent de -1", non ?
                        // on ne continue que si j = la carte ennemie envoyée à coup sûr, ou qu'on s'en fout (= on teste toutes celles qui restent)
                            carteEnnemie[j].supposeeUtilisee = true;
                            for (int k = 0 ; k <= pillz ; k++) {// Pour chaque pillz
                                pillzRestants = pillz - k;

                                if (determinQuiEstTeste)
                                    pillzTest = k;
                                for (int l = 0 ; l <= pillzEnnemis ; l++) { // Pour chaque pillz ennemi
                                    pillzEnnemisRestants = pillzEnnemis - l;
                                    jeGagne = jeRemporteLeRound(carteAlliee[i].combatAvecXPillzContreYAvecZpillz[k][j][l], nRound);

                                    modifPillzPvEtRoundSuivant(pv, pvEnnemis, pillzRestants, pillzEnnemisRestants, i, j, nRound, jeGagne, false, false, dernierRoundACalculer);

                                    if (pillzRestants >= 3) {                                    
                                        if (determinQuiEstTeste)
                                            furyUtilisee = true;

                                        modifPillzPvEtRoundSuivant(pv, pvEnnemis, pillzRestants - 3, pillzEnnemisRestants , i, j, nRound, jeGagne, true, false, dernierRoundACalculer);

                                        if (pillzEnnemisRestants >= 3)
                                            modifPillzPvEtRoundSuivant(pv, pvEnnemis, pillzRestants - 3, pillzEnnemisRestants - 3, i, j, nRound, jeGagne, true, true, dernierRoundACalculer);

                                        if (determinQuiEstTeste)
                                            furyUtilisee = false;
                                    }
                                    if (pillzEnnemisRestants >= 3)
                                        modifPillzPvEtRoundSuivant(pv, pvEnnemis, pillzRestants, pillzEnnemisRestants - 3, i, j, nRound, jeGagne, false, true, dernierRoundACalculer);
                                }
                            }
                            carteEnnemie[j].supposeeUtilisee = false; //desupposer
                        }
                    }
                }
                carteAlliee[i].supposeeUtilisee = false; // desupposer
            }
        }
    }
}
コード例 #25
0
ファイル: volume.cpp プロジェクト: Asuzer/cgal
void Volume::display_surface_mesher_result()
{
  if(m_surface.empty() || // Either the surface is not computed.
     m_view_surface) // Or it is computed and displayed, and one want
                     // to recompute it.
  {
    QTime total_time;
    total_time.start();

    values_list->save_values(fileinfo.absoluteFilePath());

    std::size_t nx = m_image.xdim();
    std::size_t ny = m_image.ydim();
    std::size_t nz = m_image.zdim();
    if(nx * ny * nz == 0)
    {
      status_message("No volume loaded.");
      return;
    }

    m_surface.clear();
    sm_timer.reset();
    busy();

    status_message("Surface meshing...");

    sm_timer.start();

    c2t3.clear();
    del.clear();
    Sphere bounding_sphere(m_image.center(),m_image.radius()*m_image.radius());

    Classify_from_isovalue_list classify(values_list);
    Generate_surface_identifiers generate_ids(values_list);

    m_image.set_interpolation(mw->interpolationCheckBox->isChecked());
    if(mw->labellizedRadioButton->isChecked()) {
      std::cerr << "Labellized image\n";
    }
    m_image.set_labellized(mw->labellizedRadioButton->isChecked());
    classify.set_identity(mw->labellizedRadioButton->isChecked());
    generate_ids.set_labellized_image(mw->labellizedRadioButton->isChecked());

    // definition of the surface
    Surface_3 surface(m_image, bounding_sphere, m_relative_precision);
//     Threshold threshold(m_image.isovalue());

    // surface mesh traits class
    typedef CGAL::Surface_mesher::Implicit_surface_oracle_3<Kernel,
      //     typedef CGAL::Surface_mesher::Image_surface_oracle_3<Kernel,
      Surface_3, 
      Classify_from_isovalue_list,
      Generate_surface_identifiers> Oracle;
    Oracle oracle(classify, generate_ids);

    if(mw->searchSeedsCheckBox->isChecked())
    {
      typedef std::vector<std::pair<Point, double> > Seeds;
      Seeds seeds;
      {
	std::cerr << "Search seeds...\n";
	std::set<unsigned char> domains;
	search_for_connected_components(std::back_inserter(seeds),
					CGAL::inserter(domains),
					classify);
	std::cerr << "Found " << seeds.size() << " seed(s).\n";

	if(mw->labellizedRadioButton->isChecked() && 
	   values_list->numberOfValues() == 0) 
	{
	  Q_FOREACH(unsigned char label, domains) {
	    if(label != 0) {
	      values_list->addValue(label);
	    }
	  }
	}
      }
      std::ofstream seeds_out("seeds.off");
      std::ofstream segments_out("segments.txt");
      seeds_out.precision(18);
      seeds_out << "OFF\n" << seeds.size() << " 0 0\n";
      segments_out.precision(18);
      for(Seeds::const_iterator it = seeds.begin(), end = seeds.end();
	  it != end; ++it)
      {
        seeds_out << it->first << std::endl;
	CGAL::Random_points_on_sphere_3<Point> random_points_on_sphere_3(it->second);
	Oracle::Intersect_3 intersect = oracle.intersect_3_object();
	for(int i = 0; i < 20; ++i)
	{
	  const Point test = it->first + (*random_points_on_sphere_3++ - CGAL::ORIGIN);
	  CGAL::Object o = intersect(surface, Segment_3(it->first, test));
	  if (const Point* intersection = CGAL::object_cast<Point>(&o)) {
            segments_out << "2 " << it->first << " " << *intersection << std::endl;
	    del.insert(*intersection);
          }
	  else 
	  {
	    std::cerr << 
	      boost::format("Error. Segment (%1%, %2%) does not intersect the surface! values=(%3%, %4%)\n")
	      % it->first % test
	      % surface(it->first) % surface(test);
	  }
	}
      }
    }
コード例 #26
0
ファイル: example-003-3D.cpp プロジェクト: gpichot/gaml
int main(int argc, char* argv[]) {

  // Let us make libsvm quiet
  gaml::libsvm::quiet();
  // random seed initialization
  std::srand(std::time(0));

  try {

    // Let us collect samples.
    
    DataSet basis;

    basis.resize(100);
    for(auto& data : basis) {
      double theta = gaml::random::uniform(0,2*M_PI);
      data = Data(theta,oracle(theta));
    }

    // Let us set configure a svm

    struct svm_parameter params;
    gaml::libsvm::init(params);
    params.kernel_type = RBF;          // RBF kernel
    params.gamma       = 1;            // k(u,v) = exp(-gamma*(u-v)^2)
    params.svm_type    = EPSILON_SVR;
    params.p           = .01;          // epsilon
    params.C           = 10;
    params.eps         = 1e-10;        // numerical tolerence

    // This sets up a svm learning algorithm for predicting a scalar.
    auto scalar_learner = gaml::libsvm::supervized::learner<double,double>(params, nb_nodes_of, fill_nodes);

    // Let us use it for learning x, y and z.
    auto learner = gaml::multidim::learner<Point,3>(scalar_learner, array_of_output, output_of_array);

    // Let us train it and get some predictor f. f is a function, as the oracle.
    std::cout << "Learning..." << std::endl;
    auto f = learner(basis.begin(), basis.end(), input_of, output_of);

    // Let us retrieve the three SVMs in order to save each one.
    auto f_predictors                   = f.predictors();
    std::array<std::string,3> filenames = {{std::string("x.pred"),"y.pred","z.pred"}};
    auto name_iter                      = filenames.begin();
    for(auto& pred : f_predictors) pred.save_model(*(name_iter++));

    // We can compute the empirical risk with gaml tools.
    auto evaluator = gaml::risk::empirical(Loss());
    double risk = evaluator(f, basis.begin(), basis.end(), input_of, output_of);
    std::cout << "Empirical risk : " << risk << std::endl
	      << "    sqrt(risk) : " << sqrt(risk) << std::endl;

    // Let us load our predictor. We need first to gather each loaded
    // scalar predictor in a collection...
    std::list<gaml::libsvm::Predictor<double,double>> predictors;
    name_iter= filenames.begin();
    for(unsigned int dim = 0; dim < 3; ++dim) {
      gaml::libsvm::Predictor<double,double> predictor(nb_nodes_of, fill_nodes);
      predictor.load_model(*(name_iter++));
      predictors.push_back(predictor);
    }
    // ... and create the 3D predictor (variable g) from the
    // collection of scalar predictors.
    gaml::multidim::Predictor<Point,
			      gaml::libsvm::Predictor<double,double>,
			      3> g(output_of_array, predictors.begin(), predictors.end());

    // let us gnuplot what we have.

    std::ofstream dataset_file("dataset.data");
    for(auto& data : basis)
      dataset_file << data.first << ' '  << data.second.x << ' ' << data.second.y << ' ' << data.second.z << std::endl;
    dataset_file.close();

    std::ofstream prediction_file("prediction.data");
    for(double theta = 0; theta <= 2*M_PI; theta += .01) {
      Point p = g(theta);
      prediction_file << theta << ' ' << p.x   << ' ' << p.y   << ' ' << p.z   << std::endl;
    }
    prediction_file.close();

    std::ofstream gnuplot_file_3d("3D.plot"); 
    gnuplot_file_3d << "set ticslevel 0" << std::endl
		    << "set xlabel 'x(theta)'" << std::endl
		    << "set ylabel 'y(theta)'" << std::endl
		    << "set zlabel 'z(theta)' " << std::endl
		    << "splot 'dataset.data' using 2:3:4 with points notitle, "
		    << "'prediction.data' using 2:3:4 with lines notitle" << std::endl;
    gnuplot_file_3d.close();
    std::cout << std::endl
	      << "Try 'gnuplot -p 3D.plot'" << std::endl;

    std::ofstream gnuplot_file_1d("1D-x.plot"); 
    gnuplot_file_1d << "set xlabel 'theta'" << std::endl
		    << "set ylabel 'x(theta)'" << std::endl
		    << "plot 'dataset.data' using 1:2 with points notitle, "
		    << "'prediction.data' using 1:2 with lines notitle" << std::endl;
    gnuplot_file_1d.close();
    std::cout << "Try 'gnuplot -p 1D-x.plot'" << std::endl
	      << std::endl;
  }
  catch(gaml::exception::Any& e) {
    std::cout << e.what() << std::endl;
  }
  
  return 0;
}
コード例 #27
0
ファイル: function.hpp プロジェクト: andrescodas/casadi
 /** [DEPRECATED] Use oracle() instead */
 Function rootfinder_fun() const { return oracle();}
コード例 #28
0
ファイル: DynamicOracleTest.cpp プロジェクト: majineu/Parser
TEST_F(DynamicOracleTest, LinearTreeLoss) {
  state_->Shift(pool_, sentence_);
  int loss = ComputeLinearTreeLoss(*state_, nodes_, CIDMap::SHIFT);
  EXPECT_EQ(0, loss);
  
  state_->Shift(pool_, sentence_);
  loss = ComputeLinearTreeLoss(*state_, nodes_, CIDMap::SHIFT);
  EXPECT_EQ(0, loss);
  
  loss = ComputeLinearTreeLoss(*state_, nodes_, CIDMap::LEFT_REDUCE);
  EXPECT_EQ(0, loss);
  
  state_->Shift(pool_, sentence_);
  state_->Shift(pool_, sentence_);
  loss = ComputeLinearTreeLoss(*state_, nodes_, CIDMap::SHIFT);
  EXPECT_EQ(2, loss);
  
  loss = ComputeLinearTreeLoss(*state_, nodes_, CIDMap::LEFT_REDUCE);
  EXPECT_EQ(0, loss);
  
  loss = ComputeLinearTreeLoss(*state_, nodes_, CIDMap::RIGHT_REDUCE);
  EXPECT_EQ(3, loss);

  loss = ComputeActionLoss(*state_, nodes_, CIDMap::SHIFT);
  EXPECT_EQ(2, loss);
  loss = ComputeActionLoss(*state_, nodes_, CIDMap::LEFT_REDUCE);
  EXPECT_EQ(0, loss);
  loss = ComputeActionLoss(*state_, nodes_, CIDMap::RIGHT_REDUCE);
  EXPECT_EQ(4, loss);

  state_->ReduceLeft(nodes_[state_->GetStack1()->Index()]->GetDepId());
  state_->ReduceLeft(nodes_[state_->GetStack1()->Index()]->GetDepId());
  state_->ReduceLeft(nodes_[state_->GetStack1()->Index()]->GetDepId());
  loss = ComputeLinearTreeLoss(*state_, nodes_, CIDMap::SHIFT);
  EXPECT_EQ(0, loss);
  
  state_->Shift(pool_, sentence_);
  state_->Shift(pool_, sentence_);
  EXPECT_EQ(5, state_->GetTopStack()->Index());
  EXPECT_EQ(4, state_->GetStack1()->Index());
  //                   2    1    0        
  // stack and queue: Inc. said it   |   expects
  loss = ComputeLinearTreeLoss(*state_, nodes_, CIDMap::SHIFT);
  EXPECT_EQ(0, loss);
  loss = ComputeLinearTreeLoss(*state_, nodes_, CIDMap::LEFT_REDUCE);
  EXPECT_EQ(3, loss);
  loss = ComputeLinearTreeLoss(*state_, nodes_, CIDMap::RIGHT_REDUCE);
  EXPECT_EQ(0, loss);
  
  // Add arc (said, it) which is a wrong action.
  //                   1    0        
  // stack and queue: Inc. said   |   expects
  state_->ReduceRight(state_->GetTopStack()->GetDepId());
  loss = ComputeLinearTreeLoss(*state_, nodes_, CIDMap::SHIFT);
  EXPECT_EQ(0, loss);

  CDynamicOracleSearcher oracle(*state_, nodes_);
  oracle.InitStackCosts();
  EXPECT_EQ(1, oracle.TopStackCost());
  EXPECT_EQ(1, oracle.TotalStackCost());
  
  oracle.ComputeStackCost(CIDMap::LEFT_REDUCE);
  EXPECT_EQ(1, oracle.TopStackCost());
  EXPECT_EQ(1, oracle.TotalStackCost());
  
  loss = ComputeLinearTreeLoss(*state_, nodes_, CIDMap::LEFT_REDUCE);
  EXPECT_EQ(0, loss);
  
  loss = ComputeActionLoss(*state_, nodes_, CIDMap::LEFT_REDUCE);
  EXPECT_EQ(1, loss);
  
//  loss = ComputeActionLoss(*state_, nodes_, CIDMap::RIGHT_REDUCE);
//  EXPECT_EQ(4, loss);
}
コード例 #29
0
Data sample() {
  X x = {{gaml::random::uniform(XMIN,XMAX),
	  gaml::random::uniform(XMIN,XMAX)}};
  return {x, oracle(x)+gaml::random::uniform(-NOISE,NOISE)};
}