Ejemplo n.º 1
0
 std::size_t binary_save(T const& t, char * buffer, std::size_t size)
 {
     fast_buffer osb(buffer, size);
     binary_oarchive<fast_buffer> bo(osb);
     bo & t;
     return bo.good() ? osb.gcount() : (bo.clear(), 0);
 }
Ejemplo n.º 2
0
int main()
{
  array<int> a(4);
  a[3] = 1;
  const array<int> b = a;
  b.dump();
  array<float> c;
  c.dump();
  c[2] = 1.1;
  c.dump();
  a = c.convertTo<int>(&float_to_int);
  a.dump();

  array<bool> bo(5);
  bo[2] = true;
  bo.dump();

  const array<int> co(2);
  try {
    co[10] = 2;
  }
  catch(std::exception & e) {
    std::cout << "catched!!" << std::endl;
  }
  
}
Ejemplo n.º 3
0
 bool binary_save(T const& t, std::ostream& os)
 {
     boost::io::ios_flags_saver saver(os);
     os.unsetf(std::ios_base::skipws);
     binary_oarchive<> bo(os);
     bo & t;
     return bo.good() ? true : (bo.clear(), false);
 }
Ejemplo n.º 4
0
int main(int argc, const char * argv[])
{
    
    std::shared_ptr<cg::BigObject> bo(new cg::BigObject());
    
    bo->run();
    
    
    return 0;

}
Ejemplo n.º 5
0
void save(Archive & ar, const Pothos::BufferChunk &t, const unsigned int)
{
    const bool is_null = not t;
    ar << is_null;
    if (is_null) return;
    const Poco::UInt32 length = Poco::UInt32(t.length);
    ar << length;
    Pothos::serialization::BinaryObject bo(t.as<void *>(), t.length);
    ar << bo;
    ar << t.dtype;
}
Ejemplo n.º 6
0
void load(Archive & ar, Pothos::BufferChunk &t, const unsigned int)
{
    t = Pothos::BufferChunk();
    bool is_null = false;
    ar >> is_null;
    if (is_null) return;
    Poco::UInt32 length = 0;
    ar >> length;
    t = Pothos::BufferChunk(size_t(length));
    Pothos::serialization::BinaryObject bo(t.as<void *>(), t.length);
    ar >> bo;
    ar >> t.dtype;
}
Ejemplo n.º 7
0
main() {
    oo( D1, x );
    oo( D1, y );
    bo( D1, DE1 );
    bo( D1, DE2 );
    oo( D2, x );
    oo( D2, y );
    bo( D2, DE1 );
    bo( D2, DE2 );
    oo( D3, x );
    oo( D3, y );
    bo( D3, DE1 );
    bo( D3, EE );
    oo( D4, x );
    oo( D4, y );
    bo( D4, EE );
    bo( D4, DE1 );
    bo( D4, DE2 );
}
Ejemplo n.º 8
0
void save(Archive & ar, const Pothos::Proxy &t, const unsigned int)
{
    auto name = t.getEnvironment()->getName();
    ar << name;

    //serialize to stringstream
    std::stringstream ss;
    t.getEnvironment()->serialize(t, ss);
    const auto buff = ss.str();

    //save length and buffer
    const Poco::UInt32 length = Poco::UInt32(buff.size());
    ar << length;
    Pothos::serialization::binary_object bo((void *)buff.data(), buff.size());
    ar << bo;
}
Ejemplo n.º 9
0
SBasis extract_u(SBasis2d const &a, double u) {
    SBasis sb(a.vs, Linear());
    double s = u*(1-u);
    
    for(unsigned vi = 0; vi < a.vs; vi++) {
        double sk = 1;
        Linear bo(0,0);
        for(unsigned ui = 0; ui < a.us; ui++) {
            bo += (extract_u(a.index(ui, vi), u))*sk;
            sk *= s;
        }
        sb[vi] = bo;
    }
    
    return sb;
}
Ejemplo n.º 10
0
SBasis extract_v(SBasis2d const &a, double v) {
    SBasis sb(a.us, Linear());
    double s = v*(1-v);
    
    for(unsigned ui = 0; ui < a.us; ui++) {
        double sk = 1;
        Linear bo(0,0);
        for(unsigned vi = 0; vi < a.vs; vi++) {
            bo += (extract_v(a.index(ui, vi), v))*sk;
            sk *= s;
        }
        sb[ui] = bo;
    }
    
    return sb;
}
Ejemplo n.º 11
0
void load(Archive & ar, Pothos::Proxy &t, const unsigned int)
{
    std::string name;
    ar >> name;
    auto env = Pothos::ProxyEnvironment::make(name);

    //extract length and buffer
    Poco::UInt32 length = 0;
    ar >> length;
    auto buff = std::vector<char>(size_t(length));
    Pothos::serialization::binary_object bo((void *)buff.data(), buff.size());
    ar >> bo;

    //deserialize from stringstream
    std::stringstream ss;
    ss.write((const char *)buff.data(), buff.size());
    t = env->deserialize(ss);
}
Ejemplo n.º 12
0
void mg_websocket_write_image(mg_connection* conn, const shared_ptr<Image>& buf, Image::ImageFileFormat ff) {
    BinaryOutput bo("<memory>", G3D_BIG_ENDIAN);

    alwaysAssertM((ff == Image::PNG) || (ff == Image::JPEG), "Only PNG and JPEG are supported right now");
    const char* mimeType = (ff == Image::PNG) ? "image/png" : "image/jpeg";
    const String& msg = 
        format("{\"type\":%d,\"width\":%d,\"height\":%d,\"mimeType\":\"%s\"}",IMAGE, buf->width(), buf->height(), mimeType);

    // JSON header length (in network byte order)
    bo.writeInt32((int32)msg.length());

    // JSON header
    bo.writeString(msg, (int32)msg.length());

    // Binary data
    buf->serialize(bo, ff);
    
    const size_t bytes = mg_websocket_write(conn, 0x2, (const char*)bo.getCArray(), bo.length());
    (void)bytes;
    // debugPrintf("Sent %d bytes\n", (unsigned int)bytes);
}
Ejemplo n.º 13
0
int							main(void)
{
	Bureaucrat		b("Connard", Bureaucrat::lowestGrade);
	Bureaucrat		bo("Boss", Bureaucrat::highestGrade);
	Form			v("Paplard vert", 1, 150);
	Form			r("Paplard rouge", 150, 1);

	std::cout << b << std::endl;
	std::cout << bo << std::endl;
	std::cout << r << std::endl;
	std::cout << v << std::endl;
	std::cout << std::endl;

	test1(b, v);
	test1(bo, v);
	test1(b, r);
	test1(bo, r);
	test3();

	return (0);
}
Ejemplo n.º 14
0
CEditArea::CEditArea(BRect frame, uint32 resizingMode)
	: BView(frame, "edit_area", resizingMode, 0)
{
BRect bo(Bounds());
BRect mainbo;
BRect rc;

	/* initilize */
	SetViewColor(B_TRANSPARENT_COLOR);
	
	mainbo = bo;
	mainbo.bottom -= SBAR_SIZE;
	mainbo.right -= (SBAR_SIZE + FL_WIDTH);
	
	/* create controls */
	int spacer_width = editor.settings.ShowSpacer ? SPACER_WIDTH : 1;
	int ln_width = editor.settings.ShowLineNumbers ? LN_WIDTH : 0;
	
	int area_lrmode = B_FOLLOW_LEFT;
	int fl_lrmode = B_FOLLOW_RIGHT;
	
	if (editor.settings.FunctionListOnLeft)
	{
		mainbo.OffsetBy(FL_WIDTH, 0);
		SWAP(area_lrmode, fl_lrmode);
	}
	

	// Line Numbers view
	rc = mainbo;
	rc.right = rc.left + (ln_width - 1);
	ln = new LNPanel(rc, B_FOLLOW_LEFT | B_FOLLOW_TOP_BOTTOM);
	AddChild(ln);
	
	// Spacer
	rc = mainbo;
	rc.left = mainbo.left + ln_width;
	rc.right = rc.left + (spacer_width - 1);
	spacer = new CSpacerView(rc, B_FOLLOW_LEFT | B_FOLLOW_TOP_BOTTOM);
	AddChild(spacer);
	
	// Command Preview panel
	rc.left = mainbo.left;
	rc.top = rc.bottom + 1;
	rc.bottom = bo.bottom;
	rc.right = rc.left+ln_width-1;
	cmd_preview = new BStringView(rc, "cmdp", "", B_FOLLOW_LEFT | B_FOLLOW_BOTTOM);
	cmd_preview->SetAlignment(B_ALIGN_RIGHT);
	AddChild(cmd_preview);
	
	// Horizontal Scrollbar
	rc.left = rc.right + 1;
	rc.right = mainbo.right;
	HScrollbar = new DocScrollBar(rc, B_FOLLOW_LEFT | B_FOLLOW_BOTTOM, B_HORIZONTAL);
	AddChild(HScrollbar);
	
	// Vertical Scrollbar
	rc.left = rc.right + 1;
	rc.right = mainbo.right + SBAR_SIZE;
	rc.bottom = rc.top - 1;
	rc.top = 0;
	VScrollbar = new DocScrollBar(rc, B_FOLLOW_RIGHT | B_FOLLOW_TOP_BOTTOM, B_VERTICAL);
	AddChild(VScrollbar);
	
	// Main Edit Area
	rc.right = rc.left - 1;
	rc.left = mainbo.left + (spacer_width + ln_width);
	editpane = new CEditPane(rc, B_FOLLOW_ALL);
	AddChild(editpane);
	
	// Corner square between H and V scrollbars
	rc.top = rc.bottom + 1;
	rc.left = rc.right + 1;
	rc.right = mainbo.right + SBAR_SIZE;
	rc.bottom = bo.bottom;
	ScrollbarCorner = new BView(rc, "corner", B_FOLLOW_BOTTOM | B_FOLLOW_RIGHT, 0);
	AddChild(ScrollbarCorner);
	
	// function list
	if (editor.settings.FunctionListOnLeft)
	{
		rc = Bounds();
		rc.right = FL_WIDTH - 1;
	}
	else
	{
		rc = bo;
		rc.left = mainbo.right + SBAR_SIZE + 1;
	}
	
	functionlist = new CFunctionList(rc, fl_lrmode | B_FOLLOW_TOP_BOTTOM);
	AddChild(functionlist);

	editpane->MakeFocus();
}
Ejemplo n.º 15
0
  // Run one valid triangle. Solve for x in
  //     P' T Q' x = R \ b,
  // where P = diag(p) and similarly for Q and R, and T is a triangle.
  static int test (const TestOptions& to, const bool print_options=false,
                   const bool exception_expected=false) {
    int nerr = 0;

    const Int max_nrhs = 3;
    const Real tol = std::numeric_limits<Real>::epsilon()*1e6;

    // Generate matrix data.
    Data d;
    Size nnz;
    {
      ut::gen_tri_matrix(to, d);     // triangle
      nnz = d.ir.back();
      ut::gen_rand_perm(d.m, d.p);   // row permutation vector
      ut::gen_rand_perm(d.m, d.q);   // col permutation vector
      ut::gen_rand_vector(d.m, d.r); // row scaling
    }

    const Int ldb = d.m + 3, ldx = d.m + 4;
    std::vector<Sclr> b(ldb*max_nrhs), xt(d.m*max_nrhs), x(ldx*max_nrhs);
    {
      // True x.
      ut::gen_rand_vector(xt.size(), xt);
      // Generate the rhs b.
      for (Int irhs = 0; irhs < max_nrhs; ++irhs) {
        const Sclr* const xtp = xt.data() + irhs*d.m;
        Sclr* const bp = b.data() + irhs*ldb;
        std::vector<Sclr> y(d.m);
        for (Int i = 0; i < d.m; ++i)
          x[i] = xtp[d.q[i]];
        ut::mvp(d, to.transpose, to.conjugate, x.data(), y.data());
        for (Int i = 0; i < d.m; ++i)
          bp[d.p[i]] = y[i];
        for (Int i = 0; i < d.m; ++i)
          bp[i] *= d.r[i];
      }
    }
    std::vector<Sclr> bo(b);

    typename ihts::CrsMatrix* T;
    typename ihts::Options opts;
    {
      T = ihts::make_CrsMatrix(d.m, d.ir.data(), d.jc.data(), d.v.data(),
                               to.transpose, to.conjugate);
      if ( ! to.reprocess && to.nthreads > 1)
        ihts::register_Deallocator(T, &d);
      if (to.solve_type == TestOptions::ls_only)
        ihts::set_level_schedule_only(opts);
      else if (to.solve_type == TestOptions::rb_only)
        opts.min_lset_size = d.m + 1;
      // To really test things well, choose very small block sizes. (This is bad
      // for performance.) These parameters are not meant to be set by the user
      // ordinarily, but they are exposed in case an expert is tuning performance
      // or, as here, for testing.
      opts.min_block_size = 6;
      opts.min_parallel_rows = 2;
      opts.pp_min_block_size = 12;
      if (to.matrix_type == TestOptions::block_sparse)
        opts.levelset_block_size = to.block_size;
    }

    {
      typename ihts::Impl* impl;
      try {
        impl = ihts::preprocess(T, max_nrhs - 1 /* For testing; see below. */,
                                to.nthreads, to.reprocess, d.p.data(), d.q.data(),
                                d.r.data(), &opts);
      } catch (...) {
        if ( ! exception_expected) {
          std::cerr << "Unexpected exception on ";
          to.print(std::cerr);
          std::cerr << "\n";
          ut::write_matrixmarket(d, "unexpected_exception.mm");
        }
        ihts::delete_CrsMatrix(T);
        throw;
      }
      if (print_options)
        ihts::print_options(impl, std::cout);
      if (to.reprocess) {
        // This isn't necessary since we aren't changing the numbers, but
        // pretend we are to test the numerical phase. Do it 3 times to test
        // idempotency.
        for (int rep = 0; rep < 3; ++rep)
          ihts::reprocess_numeric(impl, T, d.r.data());
      }
      // Exercise reset_max_nrhs.
      ihts::reset_max_nrhs(impl, max_nrhs);
      if (ihts::is_lower_tri(impl) &&
          ((to.upper && ! to.transpose) || ( ! to.upper && to.transpose)) &&
          d.m > 1 && nnz > static_cast<Size>(d.m) /* not diag */)
        ++nerr;
      for (int slv = 0; slv < 2; ++slv) {
        // Check each solve interface.
        switch (slv) {
        case 0:
          ihts::solve_omp(impl, b.data(), to.nrhs, x.data(), ldb, ldx);
          break;
        case 1:
          ihts::solve_omp(impl, b.data(), to.nrhs, x.data(), 0.0,  1.0,
                          ldb, ldx);
          ihts::solve_omp(impl, b.data(), to.nrhs, x.data(), 2.0, -1.0,
                          ldb, ldx);
          break;
        case 2:
          ihts::solve_omp(impl, b.data(), to.nrhs, ldb);
          break;
        }
        double rd = 0;
        for (Int i = 0; i < to.nrhs; ++i)
          rd = std::max(
            rd, ut::reldif(xt.data() + i*d.m,
                           (slv == 2 ? b.data() + i*ldb : x.data() + i*ldx),
                           d.m));
        if (slv == 2) b = bo;
        if (rd >= tol) {
          ++nerr;
          if (to.verbose) std::cout << "rd " << slv << ": " << rd << "\n";
        }
      }
      ihts::delete_Impl(impl);
    }

    if (to.nthreads == 1) {
      std::vector<Sclr> xb(d.m*to.nrhs), w(d.m);
      for (Int irhs = 0; irhs < to.nrhs; ++irhs) {
        const Sclr* const bp = b.data() + irhs*ldb;
        Sclr* const xbp = xb.data() + irhs*d.m;
        for (Int i = 0; i < d.m; ++i)
          xbp[i] = bp[i];
      }
      ihts::solve_serial(T, ! to.upper, xb.data(), to.nrhs, d.p.data(),
                         d.q.data(), d.r.data(), w.data());
      const double rd = ut::reldif(xt.data(), xb.data(), d.m*to.nrhs);
      if (rd >= tol) {
        ++nerr;
        if (to.verbose) std::cout << "serial rd: " << rd << "\n";
      }
    }

    ihts::delete_CrsMatrix(T);

    if (to.verbose) {
      const bool print = to.verbose == 2 || (to.verbose == 1 && nerr);
      if (print) {
        std::cout << (nerr ? "fail" : "pass") << "ed: ";
        to.print(std::cout);
        std::cout << "\n";
      }
    }

    return nerr;
  }
Ejemplo n.º 16
0
int							main(void)
{
	Bureaucrat		b("Connard", Bureaucrat::lowestGrade);
	Bureaucrat		bo("Boss", Bureaucrat::highestGrade);
	Form			*f;
	
	Intern			i;
	std::cout << std::endl;

	std::cout << "f = i.makeForm(\"Test SuC\", \"targ\");" << std::endl;
	f = i.makeForm("Test SuC", "targ");
	std::cout << "f == " << (void*)f << std::endl;
	std::cout << std::endl;
	
	
	std::cout << "f = i.makeForm(\"robotomy request\", \"Bender\");" << std::endl;
	f = i.makeForm("robotomy request", "Bender");
	std::cout << "f == " << (void*)f << std::endl; delete f;
	std::cout << std::endl;

	std::cout << "f = i.makeForm(\"robotomy requesTFORM\", \"Bender\");" << std::endl;
	f = i.makeForm("robotomy requesTFORM", "Bender");
	std::cout << "f == " << (void*)f << std::endl; delete f;
	std::cout << std::endl;
	
	std::cout << "f = i.makeForm(\"robotomy request form\", \"Bender\");" << std::endl;
	f = i.makeForm("robotomy request form", "Bender");
	std::cout << "f == " << (void*)f << std::endl; delete f;
	std::cout << std::endl;
	
	std::cout << "f = i.makeForm(\"shrubberycreation\", \"Bender\");" << std::endl;
	f = i.makeForm("shrubberycreation", "Bender");
	std::cout << "f == " << (void*)f << std::endl; delete f;
	std::cout << std::endl;

	std::cout << "f = i.makeForm(\"presidenLOLtialpardon\", \"Bender\");" << std::endl;
	f = i.makeForm("presidenLOLtialpardon", "Bender");
	std::cout << "f == " << (void*)f << std::endl;
	std::cout << std::endl;
	std::cout << std::endl;
	std::cout << std::endl;

	std::cout << "f = i.makeForm(\"presidentialpardon\", \"Bender\");" << std::endl;
	f = i.makeForm("presidentialpardon", "Bender");
	std::cout << "f == " << (void*)f << std::endl;
	std::cout << std::endl;
	
	bo.signForm(*f);
	std::cout << std::endl;
	
	bo.executeForm(*f);
	 delete f;
	std::cout << std::endl;
	std::cout << std::endl;
	
	
	
	(void)b;
	(void)bo;
	return (0);
}
Ejemplo n.º 17
0
int main(int argc, char *argv[])
{
	const char* envCfgFilename = argv[1];
	// ConfigFile cf(envCfgFilename);

	// //Read problem name, robot and environment mesh
 //    std::string name = cf.Value("problem","name");  
 //    std::string robot_name = cf.Value("problem","robot");
 //    std::string env_name = cf.Value("problem","world");

 //    //environment bounds
 //    double volume_min_x = cf.Value("problem","volume.min.x");
 //    double volume_min_y = cf.Value("problem","volume.min.y");
 //    double volume_max_x = cf.Value("problem","volume.max.x");
 //    double volume_max_y = cf.Value("problem","volume.max.y");

 //    //benchmark properties
 //    double time_limit = cf.Value("benchmark","time_limit");
 //    double mem_limit = cf.Value("benchmark","mem_limit");
 //    double run_count = cf.Value("benchmark","rount_count");
 //    std::string save_paths = cf.Value("benchmark","save_paths");

    double min_distance = 50;
    double act_distance;

	BenchmarkOptions bo(envCfgFilename);
	SE2Benchmark* b = new SE2Benchmark(bo);
	b->setup();

	boost::shared_ptr<ompl::base::SpaceInformation> spi = (b->setup_se2_)->getSpaceInformation();
	b->setup_se2_->setOptimizationObjectiveAndThreshold("length", std::numeric_limits<double>::max());
	ompl::base::StateSamplerPtr sampler_ = spi->allocStateSampler();

	ompl::base::ScopedState<ompl::base::SE2StateSpace> start(spi);
	ompl::base::ScopedState<ompl::base::SE2StateSpace> goal(spi);

	std::string path = "../env_examples/ompl/Maze_planar/benchmark";
	std::string name = "Maze";
	std::string ext = ".cfg";
	std::string cfg_file;
	
	for(int i = 1; i <= 10; i++){

		bool set_startgoal = false;

		while(!set_startgoal){
			ompl::base::State *start_state = spi->allocState();
			ompl::base::State *goal_state = spi->allocState();
			sampler_->sampleUniform(start_state);
			sampler_->sampleUniform(goal_state);

			act_distance = b->setup_se2_->getStateSpace()->distance(start_state, goal_state);

			start = start_state;
			goal = goal_state;
			if(!(b->setup_se2_->getStateValidityChecker()->isValid(start_state))) {
				printf("start no valid\n");
				continue;
			}

			if(!(b->setup_se2_->getStateValidityChecker()->isValid(goal_state))){
				printf("goal not valid\n");
			continue;
			}

			if(act_distance > min_distance){
				b->setup_se2_->setStartAndGoalStates(start, goal, 0.01);
				set_startgoal = true;
				printf("A valid state\n");
			}
			else{
				continue;
			}
		}

		 std::ostringstream convert;
	     convert << i;
	     std::string out_num = convert.str();
	     cfg_file = path + name + out_num + ext;

	 	 std::ofstream out(cfg_file.c_str());
	     out << "[problem]\n";
	     out << "name = Maze\n";//ss<< name.c_str() << "\n";
	     out << "robot = car1_planar_robot.dae\n";//<< robot_name.c_str() << "\n";
	     out << "world = Maze_planar_env.dae\n";//<< env_name.c_str() << "\n";
	     out << "start.x = "<< start->getX()<<"\n";
	     out << "start.y = "<< start->getY()<<"\n";
	     out << "start.theta = "<< start->getYaw()<<"\n";
	     out << "goal.x = "<< goal->getX()<<"\n";
	     out << "goal.y = "<< goal->getY()<<"\n";
	     out << "goal.theta = "<< goal->getYaw()<<"\n";
	     out << "volume.min.x = -55.0\n";//<< volume_min_x <<"\n";
	     out << "volume.min.y = -55.0\n";//<< volume_min_y <<"\n";
	     out << "volume.max.x = 55.0\n";//<< volume_max_x <<"\n";
	     out << "volume.max.y = 55.0\n";//<< volume_max_y <<"\n";
	     out << "\n";
	     out << "[benchmark]\n";
	     out << "time_limit= 20.0\n";// << time_limit << "\n";
	     out << "mem_limit= 10000\n";// << mem_limit << "\n";
	     out << "run_count= 10\n";// << run_count << "\n";
	     out << "save_paths=shortest\n";// << save_paths.c_str() << "\n";
	     out << "\n";
	     out << "[planner]\n";
	     out << "rrt=\n";
	     out << "#lazyrrt=\n";
	     out << "rrtstar=\n";
	     out << "rrtconnect=\n";
	     out << "prmstar=\n";
	     out << "#kpiece=\n";
	     out << "#lbkpiece=\n";


         out.close();

	}


	return 0;
}
Ejemplo n.º 18
0
/**
 * Return the backoff FST state for a given backed off FST state
 * and eventually update the set of minimal backoff nodes
 */
NeuronFstHistory FlatBOFstBuilder::getBackoff(CRnnLM &rnnlm,
                      const NeuronFstHistory &fsth,
                      set<NeuronFstHistory> &set_min_bo,
                      vector<real> &cur_cond,
                      vector<int> &words)
{
	//First test if fsth is a min BO node
	if (set_min_bo.find(fsth) != set_min_bo.end()) {
		return fsth;
	}

	// Compute number of steps
	float ratio=1.0;
	int n_bo_loops = (int) (ratio* 
	                             ((1+rnnlm.getHiddenLayerSize())*(getNumBins()-1))
	                             / max_backoff_path);
	n_bo_loops++;
	int steps = n_bo_loops;
	dprintf(1,"\nactual step is %i\n", steps);
	
	
	// Copy the current FST history
	NeuronFstHistory bo(fsth);
	NeuronFstHistory cand = NeuronFstHistory(fsth);
	int x = 0;

	real dist = 0.0;

	real uniform_logprob = mylog(1.0/rnnlm.getVocabSize());
	vector<FstHistory> candidates;
	vector<real> bo_cond(rnnlm.getVocabSize());
	vector<real> uniform_cond(rnnlm.getVocabSize(), uniform_logprob);
	real self_distance = distanceKL(uniform_cond, cur_cond);
	dprintf(2,"SELF\t%s\t%f\n", fsth.toString().c_str(), self_distance);	

	for (int s=0; s < steps; s++) {
		int min_dim = 0;
		int min_val = 0;
		real min_dist = 1e10;
		
		//browse all dimensions
		for (int i=0; i < rnnlm.getHiddenLayerSize(); i++) {
			for (x = max(0,bo.getDim(i)-1); x <= min(getNumBins()-1, bo.getDim(i)+1); x++) {
				if (bo.getDim(i) != x) {

					// Change a bit
					cand.setDim(i,x);
		
					//Compute L2 distance between the 2 conditional distributions
					bo_cond = computeSomeConditionals(rnnlm, cand, words);
		//			dist = distanceL2(tronc_cur_cond, bo_cond);
					dist = distanceKL(uniform_cond, bo_cond);
					dprintf(2,"DIM %i with X %i\t%f\n", i, x, dist);
	//	printf("CAND %i is %s\n", i, cand.toString().c_str());		
	//	printf("     dist is %f\n", dist);	
		
					// Restore to the current history
					cand.setDim(i,bo.getDim(i));
					
					//update if better
					if (dist < min_dist) {
						min_dist = dist;
						min_dim = i;
						min_val = x;
					}
				}
			}
		}
		
		//if the best bo candidate is worse than the current node
		//then the current node is a 
		if (min_dist > self_distance) {
			break;
		}
	
		dprintf(2,"CHANGE BO DIM %i = %i\tHIST %s\tDIST %f\n", min_dim, min_val, bo.toString().c_str(), min_dist);
		bo.setDim(min_dim,min_val);
		self_distance = min_dist;
		
	}
	
//			printf("src    : %s\nbo     : %s\nmin_bo: %s\n",fsth.toString().c_str(), bo.toString().c_str(), min_bo.toString().c_str());	
//	printf("MIN DIM is %i\n", min_dim);
//	dprintf("MIN STATE is %s\n", bo.toString().c_str());
//	printf("COMPARED TO  %s\n", fsth.toString().c_str());
	bo_cond = computeSomeConditionals(rnnlm, bo, words);
				
	//			dist = distanceL2(tronc_cur_cond, bo_cond);
	dist = distanceKL(uniform_cond, bo_cond);
	dprintf(2,"FINAL BO DISTANCE IS\t%f\n", dist);
	return bo;

}
Ejemplo n.º 19
0
template <class FT> int Pruner<FT>::nelder_mead_step(/*io*/ vec &b)
{
  int dn = b.size();
  int l  = dn + 1;
  evec tmp_constructor(dn);
  vector<evec> bs(l);  // The simplexe (d+1) vector of dim d
  FT *fs = new FT[l];  // Values of f at the simplex vertices

  for (int i = 0; i < l; ++i)  // Intialize the simplex
  {
    bs[i] = b;  // Start from b
    if (i < dn)
    {
      bs[i][i] += (bs[i][i] < .5) ? ND_INIT_WIDTH : -ND_INIT_WIDTH;
    }
    enforce(bs[i]);
    fs[i] = target_function(bs[i]);  // initialize the value
  }

  FT init_cf = fs[l - 1];

  vec bo(dn);  // centeroid
  FT fo;       // value at the centroid

  FT fs_maxi_last = fs[0];  // value of the last centroid

  if (verbosity)
  {
    cerr << "  Starting nelder_mead cf = " << init_cf << " proba = " << measure_metric(b) << endl;
  }
  unsigned int counter = 0;
  int mini = 0, maxi = 0, maxi2 = 0;
  while (1)  // Main loop
  {
    mini = maxi = maxi2 = 0;
    for (int i = 0; i < dn; ++i)
      bo[i] = bs[0][i];
    ////////////////
    // step 1. and 2. : Order and centroid
    ////////////////
    for (int i = 1; i < l; ++i)  // determine min and max, and centroid
    {
      mini = (fs[i] < fs[mini]) ? i : mini;
      maxi = (fs[i] > fs[mini]) ? i : maxi;
      for (int j = 0; j < dn; ++j)
      {
        bo[j] += bs[i][j];
      }
    }
    FT tmp;
    tmp = l;
    for (int i = 0; i < dn; ++i)
      bo[i] /= tmp;  // Centroid calculated

    fs_maxi_last = (!counter) ? fs[maxi] : fs_maxi_last;

    // determine min and max, and centroid
    maxi2 += (!maxi);
    for (int i = 1; i < l; ++i)
    {
      maxi2 = ((fs[i] > fs[maxi2]) && (i != maxi)) ? i : maxi2;
    }

    if (enforce(bo))  // Maybe want to skip this test, that may be kinda costly.
    {
      throw std::runtime_error("Concavity says that should not happen.");
    }

    if (verbosity)  // Not sure such verbosity is now of any use
    {
      cerr << "  melder_mead step " << counter << "cf = " << fs[mini]
           << " proba = " << measure_metric(bs[mini]) << " cost = " << single_enum_cost(bs[mini])
           << endl;
      for (int i = 0; i < dn; ++i)
      {
        cerr << ceil(bs[mini][i].get_d() * 1000) << " ";
      }
      cerr << endl;
    }

    ////////////////
    // Stopping condition (Not documented on wikipedia, improvising)
    // I'm not satistifed by it anymore. Exploration needed.
    ////////////////

    counter++;
    if (!(counter % l))  // Every l steps, we check progress and stop if none is done
    {
      if (fs[maxi] > fs_maxi_last * min_cf_decrease)
      {
        break;
      }
      fs_maxi_last = fs[maxi];
    }

    for (int i = 0; i < l; ++i)  // determine second best
    {
      if ((fs[i] > fs[maxi2]) && (i != maxi))
        maxi2 = i;
    }

    if (verbosity)
    {
      cerr << mini << " " << maxi2 << " " << maxi << endl;
      cerr << fs[mini] << " < " << fs[maxi2] << " < " << fs[maxi] << " | " << endl;
    }

    ////////////////
    // step 3. Reflection
    ////////////////

    vec br(dn);  // reflected point
    FT fr;       // Value at the reflexion point
    for (int i = 0; i < dn; ++i)
      br[i] = bo[i] + ND_ALPHA * (bo[i] - bs[maxi][i]);
    enforce(br);
    fr = target_function(br);
    if (verbosity)
    {
      cerr << "fr " << fr << endl;
    }

    if ((fs[mini] <= fr) && (fr < fs[maxi2]))
    {
      bs[maxi] = br;
      fs[maxi] = fr;
      if (verbosity)
      {
        cerr << "    Reflection " << endl;
      }
      continue;  // Go to step 1.
    }

    ////////////////
    // step 4. Expansion
    ////////////////

    if (fr < fs[mini])
    {
      vec be(dn);
      FT fe;
      for (int i = 0; i < dn; ++i)
        be[i] = bo[i] + ND_GAMMA * (br[i] - bo[i]);
      enforce(be);
      fe = target_function(be);
      if (verbosity)
      {
        cerr << "fe " << fe << endl;
      }
      if (fe < fr)
      {
        bs[maxi] = be;
        fs[maxi] = fe;
        if (verbosity)
        {
          cerr << "    Expansion A " << endl;
        }
        continue;  // Go to step 1.
      }
      else
      {
        bs[maxi] = br;
        fs[maxi] = fr;
        if (verbosity)
        {
          cerr << "    Expansion B " << endl;
        }
        continue;  // Go to step 1.
      }
    }

    ////////////////
    // step 5. Contraction
    ////////////////

    if (!(fr >= fs[maxi2]))  // Here, it is certain that fr >= fs[maxi2]
    {
      throw std::runtime_error("Something certain is false in Nelder-Mead.");
    }

    vec bc(dn);
    FT fc;
    for (int i = 0; i < dn; ++i)
      bc[i] = bo[i] + ND_RHO * (bs[maxi][i] - bo[i]);
    enforce(bc);
    fc = target_function(bc);
    if (verbosity)
    {
      cerr << "fc " << fc << endl;
    }
    if (fc < fs[maxi])
    {
      bs[maxi] = bc;
      fs[maxi] = fc;
      if (verbosity)
      {
        cerr << "    Contraction " << endl;
      }
      continue;  // Go to step 1.
    }

    ////////////////
    // step 6. Shrink
    ////////////////
    if (verbosity)
    {
      cerr << "    Shrink " << endl;
    }
    for (int j = 0; j < l; ++j)
    {
      for (int i = 0; i < dn; ++i)
      {
        bs[j][i] = bs[mini][i] + ND_SIGMA * (bs[j][i] - bs[mini][i]);
      }
      enforce(bs[j]);
      fs[j] = target_function(bs[j]);  // initialize the value
    }
  }

  b            = bs[mini];
  int improved = (init_cf * min_cf_decrease) > fs[mini];

  if (verbosity)
  {
    cerr << "Done nelder_mead, after " << counter << " steps" << endl;
    cerr << "Final cf = " << fs[mini] << " proba = " << measure_metric(b) << endl;
    if (improved)
    {
      cerr << "Progress has been made: init cf = " << init_cf << endl;
    }
    cerr << endl;
  }

  return improved;  // Has MN made any progress
}
Ejemplo n.º 20
0
 bool binary_save(T const& t, std::streambuf& osb)
 {
     binary_oarchive<> bo(osb);
     bo & t;
     return bo.good() ? true : (bo.clear(), false);
 }
Ejemplo n.º 21
0
void testInts()
{
	cout << "Testing with a simple data type: integers" << endl;
	cout << "First, we'll test the constructors:" << endl;

	cout << "Testing the default constructor, row and column should = 0)" << endl;
	Array2D<int> blob;
	cout << "Rows: " << blob.getRow() << " Columns: " << blob.getColumn() << endl << endl;

	cout << "Testing the constructor with both rows and columns defined at initialization: " << endl;
	Array2D<int> boo(3, 5);
	cout << "Rows: " << boo.getRow() << " Columns: " << boo.getColumn() << endl << endl;

	cout << "Testing subscript operators with valid input: " << endl;
	initializeArrayInts(boo);
	printArray(boo);

	cout << "Testing copy constructor: " << endl;
	Array2D<int> bo(boo);
	cout << "Rows: " << bo.getRow() << " Columns: " << bo.getColumn() << endl << endl;
	printArray(bo);

	cout << "Testing the assignment operator: " << endl;
	blob = bo;
	cout << "Rows: " << blob.getRow() << " Columns: " << blob.getColumn() << endl << endl;
	printArray(blob);

	cout << "Now testing mutator functions for both rows and columns: " << endl << endl;
	cout << "First with adding rows: " << endl;
	boo.setRow(6);
	cout << "Rows: " << boo.getRow() << " Columns: " << boo.getColumn() << endl << endl;
	initializeArrayInts(boo);
	printArray(boo);

	cout << "Now deleting rows: " << endl;
	boo.setRow(3);
	cout << "Rows: " << boo.getRow() << " Columns: " << boo.getColumn() << endl << endl;
	printArray(boo);

	cout << "Now passing an invalid row length: " << endl;
	try
	{
		boo.setRow(-1);
	}
	catch (Exception &except)
	{
		cout << except << endl << endl;
	}

	cout << "Now adding columns (maintains data position in current rows/columns): " << endl;
	boo.setColumn(7);
	cout << "Rows: " << boo.getRow() << " Columns: " << boo.getColumn() << endl << endl;
	printArray(boo);

	cout << "Now deleting columns (maintains data position in current rows/columns which are being kept): " << endl;
	boo.setColumn(5);
	cout << "Rows: " << boo.getRow() << " Columns: " << boo.getColumn() << endl << endl;
	printArray(boo);

	cout << "Now passing invalid value for column: " << endl;
	try
	{
		boo.setColumn(-1);
	}
	catch (Exception &except)
	{
		cout << except << endl << endl;
	}
	cout << "Rows: " << boo.getRow() << " Columns: " << boo.getColumn() << endl << endl;
	printArray(boo);

	cout << "Testing subscipt operator access on a const object: " << endl;
	const Array2D<int> const_boo(boo);
	printArray(const_boo);

}
BlockOption BlockOption::makeInteger(QString displayName, QString defaultValue, int minimum, int maximum) {
    BlockOption bo(displayName, defaultValue, BLOCK_OPTION_TYPE_INTEGER);
    bo.m_minimum = minimum;
    bo.m_maximum = maximum;
    return bo;
}
BlockOption BlockOption::makeComboBox(QString displayName, QString defaultValue, QMap<QString, QString> choices) {
    BlockOption bo(displayName, defaultValue, BLOCK_OPTION_TYPE_COMBOBOX);
    bo.m_choices = choices;
    return bo;
}
Ejemplo n.º 24
0
int main(int , char**)
{

    std::cout << "Starting hard_work, ready?";
    std::cin.ignore(); 
    std::thread my_thread(hard_work);
    my_thread.join();

    std::cout << "Starting background_task, ready?";
    std::cin.ignore();
    background_task bt;
    bt();
    std::thread my_thread2(bt);
    //std::thread my_thread2({background_task()});
    my_thread2.join();

    std::cout << "Starting lambda, ready?";
    std::cin.ignore();
    std::thread my_thread3(
        []() 
        {
            hard_work();
            more_hard_work_after_hard_work();
        });
    my_thread3.join();

    std::cout << "ready to crash?";
    std::cin.ignore();
    {
        std::thread my_thread(
        []() 
        {
            hard_work();
            more_hard_work_after_hard_work();
        });
        my_thread.detach();
    }

    {
        std::cout << "ready to pass arguments?" << std::endl;
        std::cin.ignore();
        int a = 42;
        std::thread my_thread(foo, a, "soy un thread!");
        std::string str = "soy otro thread";
        std::thread my_thread2([](int a1, const std::string& a2) { std::cout << "t2: a1=" << a1 << " a2=" << a2 << std::endl; }, a, str);
        std::thread my_thread2_capture([&]() { std::cout << "t2 capturing: a1=" << a << " a2=" << str << std::endl; });
        background_task_with_args bt1;
        std::thread my_thread3(bt1,a, "casi el final...");
        background_task_with_args_in_ctor bt2(a, "el final del todo");
        std::thread my_thread4(bt2);

        my_thread.join();
        my_thread2.join();
        my_thread2_capture.join();
        my_thread3.join();
        my_thread4.join();

    }
    {

        //std::cout << "ready to pass arguments (oops)?" << std::endl;
        //std::cin.ignore();
        //ooops(1000);
        //std::cin.ignore();
    }
    {
        std::unique_ptr<big_object> bo(new big_object);
        bo->load("machodedatos.raw");
        //std::thread process_thread(process_big_object, std::move(bo));
        //process_thread.join();
    }
    {
        std::thread r_thread = return_thread();
        join_thread(std::move(r_thread));
    }
    {
        std::cout << "ready to pass arguments with ScopedThread?" << std::endl;
        std::cin.ignore();
        int a = 42;
        ScopedThread my_thread(std::thread(foo, a, "soy un thread!"));
        std::string str = "soy otro thread";
        ScopedThread my_thread2(std::thread([](int a1, const std::string& a2) { std::cout << "t2: a1=" << a1 << " a2=" << a2 << std::endl; }, a, str));
        ScopedThread my_thread3(std::thread([&]() { std::cout << "t2 capturing: a1=" << a << " a2=" << str << std::endl; }));
        background_task_with_args bt1;
        ScopedThread my_thread4(std::thread(bt1,a, "casi el final..."));
        background_task_with_args_in_ctor bt2(a, "el final del todo");
        ScopedThread my_thread5((std::thread(bt2)));
    }

    {
        std::cout << "ready to count cpus?" << std::endl;
        std::cin.ignore();
        std::cout << "num of cpus:" << std::thread::hardware_concurrency() << std::endl;
    }

    {
        std::cout << "ready to check ids?" << std::endl;
        std::cin.ignore();
        std::cout << "main thread id=" << std::this_thread::get_id() << std::endl;
        std::thread t(check_id);
        std::thread::id id = t.get_id();
        t.join();
        std::cout << "thread id=" << id << std::endl;
    }

    {
        std::cout << "ready to fill and find in a list?" << std::endl;
        std::cin.ignore();
        auto producer_function = [](unsigned int numelements)
        {
            for(unsigned int i=0;i<numelements;i++)
            {
                add_to_list(i);
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
        };
        ScopedThread thread_producer1(std::thread(producer_function,100));
        ScopedThread thread_producer2(std::thread(producer_function,100));
        auto finder_function = [](unsigned int value_to_find) 
        {
            auto attempts = 0u;
            bool found = false;
            while(!found && attempts < 100)
            {
                found = contains_in_list(value_to_find);
                attempts++;
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
            if(found)
                std::cout << std::this_thread::get_id() << ": Found! after " << attempts << " attempts" << std::endl;
            else
                std::cout << std::this_thread::get_id() << ": not found! :(" << std::endl;
        };
        ScopedThread thread_finder1(std::thread(finder_function,88));
        ScopedThread thread_finder2(std::thread(finder_function,101));
    }
    {

        std::cout << "ready to crush a stack?" << std::endl;
        std::cin.ignore();
        std::stack<int> s;
        s.push(42);
        if(!s.empty())
        {
            int const value = s.top();
            s.pop();
            foo(value, "do_something");
        }
        std::atomic<int> producersWorking(0);
        std::atomic<bool> started(false);
        ThreadSafeStack<int> ts;
        auto producer_function = [&started, &producersWorking](ThreadSafeStack<int>& ts, unsigned int numelements)
        {
            producersWorking++;
            started = true;
            for(unsigned int i=0;i<numelements;i++)
            {
                ts.push(i);
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
            producersWorking--;
        };
        auto consumer_function = [&started, &producersWorking](ThreadSafeStack<int>& ts)
        {
            while (!started) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); }
            while(producersWorking > 0)
            {
                int value;
                if (ts.pop(value))
                {
                    std::cout << std::this_thread::get_id() << ":popped value=" << value << std::endl;
                    std::this_thread::sleep_for(std::chrono::milliseconds(10));
                }
            }
            std::cout << std::this_thread::get_id() << ":stack is empty" << std::endl;
        };
        ScopedThread thread_producer1(std::thread(producer_function,std::ref(ts),100));
        ScopedThread thread_producer2(std::thread(producer_function,std::ref(ts),100));
        ScopedThread thread_producer3(std::thread(producer_function, std::ref(ts), 100));
        ScopedThread thread_producer4(std::thread(producer_function, std::ref(ts), 100));
        ScopedThread thread_consumer1(std::thread(consumer_function,std::ref(ts)));
        ScopedThread thread_consumer2(std::thread(consumer_function,std::ref(ts)));
        ScopedThread thread_consumer3(std::thread(consumer_function, std::ref(ts)));
    }

    return EXIT_SUCCESS;
}