Ejemplo n.º 1
0
static void
sse_test (void)
{
  assert (ys (1) == xs ());
  assert (ys (2) == xs () * 2);
  assert (yd (1) == xd ());
  assert (yd (2) == xd () * 2);
}
Ejemplo n.º 2
0
void
print_line(line* t)
{
	fprintf(outfile, "newpath\n");
	fprintf(outfile, "4 setlinewidth\n");
	fprintf(outfile, "0.3 setgray\n");
	fprintf(outfile, "%f %f moveto\n", xs(t->v1[0]), ys(t->v1[1]));
	fprintf(outfile, "%f %f lineto\n", xs(t->v2[0]), ys(t->v2[1]));
	fprintf(outfile, "stroke\n");
}
Ejemplo n.º 3
0
void
print_proj_xy(triangle* t)
{
	fprintf(outfile, "newpath\n");
	fprintf(outfile, "0.2 setlinewidth\n");
	fprintf(outfile, "%f %f moveto\n", xs(t->v1[0]), ys(t->v1[1]));
	fprintf(outfile, "%f %f lineto\n", xs(t->v2[0]), ys(t->v2[1]));
	fprintf(outfile, "%f %f lineto\n", xs(t->v3[0]), ys(t->v3[1]));
	fprintf(outfile, "%f %f lineto\n", xs(t->v1[0]), ys(t->v1[1]));
	fprintf(outfile, "stroke\n");

}
Ejemplo n.º 4
0
void
MockReadonlyIndex::build(SortableStrVec& keys) {
	const Schema* schema = m_schema;
	const byte* base = keys.m_strpool.data();
	size_t fixlen = schema->getFixedRowLen();
	if (fixlen) {
		assert(keys.m_index.size() == 0);
		assert(keys.str_size() % fixlen == 0);
		m_ids.resize_no_init(keys.str_size() / fixlen);
		for (size_t i = 0; i < m_ids.size(); ++i) m_ids[i] = i;
		std::sort(m_ids.begin(), m_ids.end(), [=](size_t x, size_t y) {
			fstring xs(base + fixlen * x, fixlen);
			fstring ys(base + fixlen * y, fixlen);
			int r = schema->compareData(xs, ys);
			if (r) return r < 0;
			else   return x < y;
		});
	}
	else {
		if (keys.str_size() >= UINT32_MAX) {
			THROW_STD(length_error,
				"keys.str_size=%lld is too large", llong(keys.str_size()));
		}
		// reuse memory of keys.m_index
		auto offsets = (uint32_t*)keys.m_index.data();
		size_t rows = keys.m_index.size();
		m_ids.resize_no_init(rows);
		for (size_t i = 0; i < rows; ++i) m_ids[i] = i;
		for (size_t i = 0; i < rows; ++i) {
			uint32_t offset = uint32_t(keys.m_index[i].offset);
			offsets[i] = offset;
		}
		offsets[rows] = keys.str_size();
		std::sort(m_ids.begin(), m_ids.end(), [=](size_t x, size_t y) {
			size_t xoff0 = offsets[x], xoff1 = offsets[x+1];
			size_t yoff0 = offsets[y], yoff1 = offsets[y+1];
			fstring xs(base + xoff0, xoff1 - xoff0);
			fstring ys(base + yoff0, yoff1 - yoff0);
			int r = schema->compareData(xs, ys);
			if (r) return r < 0;
			else   return x < y;
		});
		BOOST_STATIC_ASSERT(sizeof(SortableStrVec::SEntry) == 4*3);
		m_keys.offsets.risk_set_data(offsets);
		m_keys.offsets.risk_set_size(rows + 1);
		m_keys.offsets.risk_set_capacity(3 * rows);
		m_keys.offsets.shrink_to_fit();
		keys.m_index.risk_release_ownership();
	}
	m_keys.strpool.swap((valvec<char>&)keys.m_strpool);
	m_fixedLen = fixlen;
}
Ejemplo n.º 5
0
int main()
{
  unsigned long cpu_facilities;

  cpu_facilities = i386_cpuid ();

  if (cpu_facilities & bit_SSE)
    {
      assert (ys (1) == xs ());
      assert (ys (2) == xs () * 2);
      assert (yd (1) == xd ());
      assert (yd (2) == xd () * 2);
    }
  return 0;
}
Ejemplo n.º 6
0
	// Evaluate this model at x
	double GaussMixtureEvaluator::EvaluateLog(const VecD& x) const {
		VecD ys(gm.ncomps);
		for (int i = 0; i < gm.ncomps; i++) {
			ys[i] = evaluators[i]->EvaluateLog(x) + logweights[i];
		}
		return LogSumExp(ys);
	}
Ejemplo n.º 7
0
static bool quick_reject_in_y(const SkPoint pts[4], const SkRect& clip) {
    Sk4s ys(pts[0].fY, pts[1].fY, pts[2].fY, pts[3].fY);
    Sk4s t(clip.top());
    Sk4s b(clip.bottom());

    return (ys < t).allTrue() || (ys > b).allTrue();
}
Ejemplo n.º 8
0
/*
 * For converting default values specified in nodespec
 */
Value toValue(const std::string& yamlstring, NTA_BasicType dataType)
{
    // IMemStream s(yamlstring, ::strlen(yamlstring));

    // yaml-cpp bug: append a space if it is only one character
    // This is very inefficient, but should be ok since it is
    // just used at construction time for short strings
    std::string paddedstring(yamlstring);
    if (paddedstring.size() < 2)
        paddedstring = paddedstring + " ";
    std::stringstream s(paddedstring);

    // TODO -- return value? exceptions?
    bool success = false;
    YAML::Node doc;
    try
    {
        YAML::Parser parser(s);
        success = parser.GetNextDocument(doc);
        // } catch(YAML::ParserException& e) {
    } catch(...) {
        success = false;
    }
    if (!success)
    {
        std::string ys(paddedstring);
        if (ys.size() > 30)
        {
            ys = ys.substr(0, 30) + "...";
        }
        NTA_THROW << "Unable to parse YAML string '" << ys << "' for a scalar value";
    }
    Value v = toValue(doc, dataType);
    return v;
}
Ejemplo n.º 9
0
Trajectory Trajectory::generatePolynomialTrajectory(const VectorXd& ts, const VectorXd& y_from, const VectorXd& yd_from, const VectorXd& ydd_from,
        const VectorXd& y_to, const VectorXd& yd_to, const VectorXd& ydd_to)
{
    VectorXd a0 = y_from;
    VectorXd a1 = yd_from;
    VectorXd a2 = ydd_from / 2;

    VectorXd a3 = -10 * y_from - 6 * yd_from - 2.5 * ydd_from + 10 * y_to - 4 * yd_to + 0.5 * ydd_to;
    VectorXd a4 = 15 * y_from + 8 * yd_from + 2 * ydd_from - 15  * y_to  + 7 * yd_to - ydd_to;
    VectorXd a5 = -6 * y_from - 3 * yd_from - 0.5 * ydd_from  + 6 * y_to  - 3 * yd_to + 0.5 * ydd_to;

    int n_time_steps = ts.size();
    int n_dims = y_from.size();

    MatrixXd ys(n_time_steps,n_dims), yds(n_time_steps,n_dims), ydds(n_time_steps,n_dims);

    for (int i = 0; i < ts.size(); i++)
    {
        double t = (ts[i] - ts[0]) / (ts[n_time_steps - 1] - ts[0]);
        ys.row(i) = a0 + a1 * t + a2 * pow(t, 2) + a3 * pow(t, 3) + a4 * pow(t, 4) + a5 * pow(t, 5);
        yds.row(i) = a1 + 2 * a2 * t + 3 * a3 * pow(t, 2) + 4 * a4 * pow(t, 3) + 5 * a5 * pow(t, 4);
        ydds.row(i) = 2 * a2 + 6 * a3 * t + 12 * a4 * pow(t, 2) + 20 * a5 * pow(t, 3);
    }

    yds /= (ts[n_time_steps - 1] - ts[0]);
    ydds /= pow(ts[n_time_steps - 1] - ts[0], 2);

    return Trajectory(ts, ys, yds, ydds);
}
Ejemplo n.º 10
0
Trajectory Trajectory::generateMinJerkTrajectory(const VectorXd& ts, const VectorXd& y_from, const VectorXd& y_to)
{
    int n_time_steps = ts.size();
    int n_dims = y_from.size();

    MatrixXd ys(n_time_steps,n_dims), yds(n_time_steps,n_dims), ydds(n_time_steps,n_dims);

    double D =  ts[n_time_steps-1];
    ArrayXd tss = (ts/D).array();


    ArrayXd A = y_to.array()-y_from.array();

    for (int i_dim=0; i_dim<n_dims; i_dim++)
    {

        // http://noisyaccumulation.blogspot.fr/2012/02/how-to-decompose-2d-trajectory-data.html

        ys.col(i_dim)   = y_from[i_dim] + A[i_dim]*(  6*tss.pow(5)  -15*tss.pow(4) +10*tss.pow(3));

        yds.col(i_dim)  =             (A[i_dim]/D)*( 30*tss.pow(4)  -60*tss.pow(3) +30*tss.pow(2));

        ydds.col(i_dim) =         (A[i_dim]/(D*D))*(120*tss.pow(3) -180*tss.pow(2) +60*tss       );
    }

    return Trajectory(ts,ys,yds,ydds);


}
Ejemplo n.º 11
0
arma::field<arma::Cube<double>> VanillaFeedForward::feedForward(
		const arma::field<arma::Cube<double>>& xs) {
	mxs = xs;
	arma::field<arma::Cube<double>> ys(xs.size());
	for (unsigned int i = 0; i < xs.size(); ++i) {
		ys[i] = feedForward(xs[i]);
	}
	return ys;
}
Ejemplo n.º 12
0
void print_circle()
{
	fprintf(outfile, "newpath\n");
	fprintf(outfile, "0 setgray\n");
	fprintf(outfile, "1 setlinewidth\n");
	fprintf(outfile, "%f %f %f 0 360 arc\n", 
		(double)(xs(0)), (double)(ys(0)), (double)((xs(RADIUS))-(xs(0))));
	fprintf(outfile, "stroke\n");
	
} 
Ejemplo n.º 13
0
arma::field<arma::Cube<double>> Softmax::feedForward(const arma::field<arma::Cube<double>>& xs) {
	arma::field<arma::Cube<double>> ys(xs.size());
	for (unsigned int i=0; i<xs.size(); ++i) {
		double m = fmax(0.0, xs[i].max());
		const arma::Cube<double>& xStable = xs[i]-m;
		arma::Cube<double> expX = arma::exp(xStable);
		ys[i] = expX / arma::accu(expX);
	}
	mYs = ys;
	return ys;
}
Ejemplo n.º 14
0
box
wide_check_box (path ip, SI x1, SI x2, pencil pen) {
    SI width, height;
    get_wide_parameters (x1, x2, pen, width, height);
    array<box> bs (2);
    array<SI>  xs (2);
    array<SI>  ys (2);
    xs[0]= ys[0]= xs[1]= ys[1]= 0;
    bs[0]= line_box (decorate_middle (ip), 0, height, width/2, 0, pen);
    bs[1]= line_box (decorate_middle (ip), width/2, 0, width, height, pen);
    return composite_box (ip, bs, xs, ys);
}
Ejemplo n.º 15
0
void GaussianProcess::observe(double x, double y)
{
	stale = true;
	last_x_size = xs.size();
	const unsigned int x_size = xs.size();
	const unsigned int y_size = ys.size();

	xs.resize(x_size+1);
	ys.resize(y_size+1);

	xs(x_size) = x;
	ys(y_size) = y;
}
Ejemplo n.º 16
0
void print_number(triangle* t, int n)
{
	float xbar, ybar;

	xbar = (t->v1[0] + t->v2[0] + t->v3[0])/3;
	ybar = (t->v1[1] + t->v2[1] + t->v3[1])/3;
	
	fprintf(outfile,"newpath\n");
	fprintf(outfile,"%f %f moveto\n", xs(xbar), ys(ybar));
	fprintf(outfile,"(%d) show\n", n);
	fprintf(outfile,"stroke\n");
	
}
Ejemplo n.º 17
0
//---------------------------------------------------------
double NNetwork::_network_cost(const arma::mat& y)
{
    double m = y.n_rows;
    arma::mat ys = arma::zeros<arma::mat>(y.n_rows, _classCount);
    for(unsigned i = 0; i < y.n_rows; i++){
        for(unsigned j = 0; j < _classCount; j++){
                ys(i,j) = ((y(i) == j) ? 1 : 0);
        }
    }
    // acquire the first pre-delta value with ys
    const arma::mat a = _as.back();

    arma::mat delta = (a - ys);
    _ds.push_back( delta );

    // calculate the regularization parameter
    double rc  = 0.0;

    std::vector<arma::mat>::const_iterator tc = _ts.begin();
    std::vector<arma::mat>::const_iterator te = _ts.end();

    // sum the sums of the squares of the non-biased coefficients
    while(tc != te){
        const arma::mat& theta = *tc;
        const arma::mat ts = theta.cols(1, theta.n_cols - 1);

        rc += arma::accu(arma::square(ts));

        tc++;
    }

    double reg = (_lambda / (2.0 * m)) * rc;

    // std::cout << "Cost reg is " << reg << std::endl;

    arma::mat log_a  = arma::log(a);
    arma::mat neg_ys = -ys;
    arma::mat non_ys = (1.0 - ys);
    arma::mat non_a  = arma::log( (1.0 - a) );

    arma::mat es = ( (neg_ys % log_a) - (non_ys % non_a) ) ;

    // J is the cost or the overall performace of the network
    // this number needs to be as close to 0 as possible
    // for accurate predictions
    double J = (1.0 / m) * arma::accu(es) + reg;

    return J;
}
Ejemplo n.º 18
0
 ExecStatus
 Distinct<View0,View1>::propagate(Space& home, const ModEventDelta&) {
   assert(x0.assigned()||x1.assigned());
   if (x0.assigned()) {
     GlbRanges<View0> xr(x0);
     IntSet xs(xr);
     ConstSetView cv(home, xs);
     GECODE_REWRITE(*this,(DistinctDoit<View1>::post(home(*this),x1,cv)));
   } else {
     GlbRanges<View1> yr(x1);
     IntSet ys(yr);
     ConstSetView cv(home, ys);
     GECODE_REWRITE(*this,(DistinctDoit<View0>::post(home(*this),x0,cv)));
   }
 }
Ejemplo n.º 19
0
box
wide_sqobr_box (path ip, SI x1, SI x2, pencil pen) {
    SI penw= pen->get_width ();
    pencil demipen= pencil (pen->get_color (), penw/2);
    path dip= decorate_middle (ip);
    SI width= max (x2-x1, 6*penw), height= 6*penw;
    array<box> bs (3);
    array<SI>  xs (3);
    array<SI>  ys (3);
    xs[0]= ys[0]= xs[1]= ys[1]= xs[2]= ys[2]= 0;
    bs[0]= line_box (dip, 0, height, width, height, pen);
    bs[1]= line_box (dip, 0, height, 0, 0, demipen);
    bs[2]= line_box (dip, width, height, width, 0, demipen);
    return composite_box (ip, bs, xs, ys);
}
Ejemplo n.º 20
0
void MainWindow::setInitialTimeDisplay(int start)
{
    std::size_t ncols = _vm["file.ncols"].as<int>();
    std::size_t nrows = _vm["file.nrows"].as<int>();
    //TODO: move plotting to appropiate method
    std::size_t numofplottedsamples = _vm["plot.num.samples"].as<int>();
    _gridPlot->p->detachItems();
    _gridPlot->setoffset(start);

    double interrowoffset = _vm["inter.row.offset"].as<double>();

    for (std::size_t row=0; row<nrows; ++row){
//    for (std::size_t row=0; row<1; ++row){
        std::vector<double> xs(numofplottedsamples);
        std::vector<double> ys(numofplottedsamples);

        std::stringstream strst;
        std::string strTitle = "Row";
        strst << strTitle << "-" << row;
        strTitle = strst.str();
        QwtPlotCurve *tscurve = new QwtPlotCurve((char *)strTitle.c_str());

        for (std::size_t x = 0; x < numofplottedsamples; ++x)
        {
            if (x+start<ncols){
		    xs[x] = (x+start)/_gridPlot->gridXpixelsperunit; //position in seconds
		    if (_bf!=NULL) {
			    ys[x] = row*interrowoffset + (*_bf)(row,x+start)/_gridPlot->gridYpixelsperunit; //y value of that sample
		    } else if (_bfsi!=NULL) {
			    ys[x] = row*interrowoffset + (*_bfsi)(row,x+start)/_gridPlot->gridYpixelsperunit; //y value of that sample
		    }
            }
        }

        tscurve->setSamples(&xs[0],&ys[0],xs.size());
        tscurve->setPen(QPen(Qt::black));

        QwtPlotMarker *rowNameText = new QwtPlotMarker();
        rowNameText->setLabel(QString(strTitle.c_str()));
        rowNameText->setXValue(xs[0]+0.25);
        rowNameText->setYValue(row*interrowoffset-0.5);
        rowNameText->attach(_gridPlot->p);

        tscurve->attach(_gridPlot->p);
    }
    _gridPlot->resetzoom();
}
Ejemplo n.º 21
0
box
wide_vect_box (path ip, SI x1, SI x2, pencil pen) {
    SI penw= pen->get_width ();
    SI width, height, arrow= 2*penw, delta=penw/2;
    get_wide_parameters (x1, x2, pen, width, height);
    height= 10*penw;
    array<box> bs (3);
    array<SI>  xs (3);
    array<SI>  ys (3);
    xs[0]= ys[0]= xs[1]= ys[1]= xs[2]= ys[2]= 0;
    bs[0]= line_box (decorate_middle (ip), 0, arrow, width, arrow, pen);
    bs[1]= line_box (decorate_middle (ip),
                     width- arrow- delta, 0, width, arrow, pen);
    bs[2]= line_box (decorate_middle (ip),
                     width+ delta- arrow, 2*arrow, width, arrow, pen);
    return composite_box (ip, bs, xs, ys);
}
Ejemplo n.º 22
0
 ExecStatus
 Distinct<View0,View1>::post(Home home, View0 x, View1 y) {
   if (x.assigned()) {
     GlbRanges<View0> xr(x);
     IntSet xs(xr);
     ConstSetView cv(home, xs);
     GECODE_ES_CHECK((DistinctDoit<View1>::post(home,y,cv)));
   }
   if (y.assigned()) {
     GlbRanges<View1> yr(y);
     IntSet ys(yr);
     ConstSetView cv(home, ys);
     GECODE_ES_CHECK((DistinctDoit<View0>::post(home,x,cv)));
   }
   (void) new (home) Distinct<View0,View1>(home,x,y);
   return ES_OK;
 }
Ejemplo n.º 23
0
std::vector<receiverStruct>
receiver::getReceiversFromOptions()
{
	// get number of receivers
	PetscInt numReceivers;
	PetscOptionsGetInt(NULL, "--number_of_receivers", &numReceivers, NULL);

	// get base directory for where to write receivers
	char dumC[PETSC_MAX_PATH_LEN];
	PetscOptionsGetString(NULL, "--base_write_directory", 
					   	  dumC,
					   	  PETSC_MAX_PATH_LEN, NULL);
	std::string baseName = dumC;
	PetscOptionsGetString(NULL, "--iteration_name",
						  dumC, PETSC_MAX_PATH_LEN, NULL);
	baseName += "/" + std::string(dumC) + "/receivers";

	// make the base dir
	if (MPI::COMM_WORLD.Get_rank() == 0)
	{
		mkdir(baseName.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
	}

	// get receiver parameters
	char *names[numReceivers]; PetscBool dumB = PETSC_FALSE;
	std::vector<PetscScalar> xs(numReceivers);
	std::vector<PetscScalar> ys(numReceivers);
	PetscOptionsGetStringArray(NULL, "--receiver_names", names, &numReceivers, NULL);
	PetscOptionsGetScalarArray(NULL, "--receiver_x", xs.data(), &numReceivers, NULL);
	PetscOptionsGetScalarArray(NULL, "--receiver_y", ys.data(), &numReceivers, NULL);
	PetscOptionsGetBool(NULL, "--write_receivers", &dumB, NULL);

	// add to structures
	std::vector<receiverStruct> receivers;
	for (auto i=0; i<numReceivers; i++)
	{
		receiverStruct r;
		r.name = baseName + "/" + names[i] + ".txt";
		r.xLoc = xs[i];
		r.yLoc = ys[i];
		r.write = dumB;
		receivers.push_back(r);
	}
	return receivers;
}
Ejemplo n.º 24
0
box
typeset_as_box (edit_env env, tree t, path ip) {
  box b= typeset_as_concat (env, t, ip);

  SI ox= 0;
  int i, n=N(b);
  for (i=0; i<n; i++)
    if (b[i]->w() != 0)
      ox= b[i]->x1;

  array<box> bs (1);
  array<SI>  xs (1);
  array<SI>  ys (1);
  bs[0]= b;
  xs[0]= ox;
  ys[0]= 0;
  return composite_box (ip, bs, xs, ys);
}
Ejemplo n.º 25
0
void SerialMonitor::newFrame(Frame frame){
	QVector<double> ys(3);

	ys[0] = frame.gx;
	ys[1] = frame.gy;
	ys[2] = frame.gz;
	((Plotter*)(subWindows[0]->widget()))->newData(frame.time, ys);

	ys[0] = frame.ax;
	ys[1] = frame.ay;
	ys[2] = frame.az;
	((Plotter*)(subWindows[1]->widget()))->newData(frame.time, ys);

	ys[0] = frame.mx;
	ys[1] = frame.my;
	ys[2] = frame.mz;
	((Plotter*)(subWindows[2]->widget()))->newData(frame.time, ys);
}
Ejemplo n.º 26
0
////////////////////////////////////////////////////////////////////////////////////////////////////////
//get_subwindow with repeated values
cv::Mat get_subwindow(cv::Rect r, const cv::Mat & img)
{
	std::vector<int> xs(r.width);
	cv::Mat out(r.height,r.width,CV_8U);

	for (int i = 0; i < r.width; i++)
	{
		xs[i] = r.x + i;
		if (xs[i] < 0)
		{
			xs[i] = 0;
		}
		else if (xs[i] >= img.cols)
		{
			xs[i] = img.cols-1;
		}
	}

	std::vector<int> ys(r.height);

	for (int i = 0; i < r.height; i++)
	{
		ys[i] = r.y + i;
		if (ys[i] < 0)
		{
			ys[i] = 0;
		}
		else if (ys[i] >= img.rows)
		{
			ys[i] = img.rows-1;
		}
	}

	for (int i = 0; i < r.width; i++)
	{
		for (int j = 0; j < r.height; j++)
		{
			out.at<unsigned char>(j,i) = img.at<unsigned char>(ys[j],xs[i]);
		}
	}
	//cv::imshow("subwindow",out.clone());
	return out.clone();
}
Ejemplo n.º 27
0
box
wide_tilda_box (path ip, SI x1, SI x2, pencil pen) {
    SI width, height, w, h, uw, hh;
    get_wide_parameters (x1, x2, pen, width, height);
    h = height/2;
    hh= (SI) (0.8660254 * ((double) h));
    w = width;
    uw= (SI) (((double) w) / 4.2679492);
    array<box> bs (3);
    array<SI>  xs (3);
    array<SI>  ys (3);
    xs[0]= ys[0]= xs[1]= ys[1]= xs[2]= ys[2]= 0;
    bs[0]= arc_box (decorate_middle (ip),
                    0, -h, 2*uw, h, 60<<6, 180<<6, pen);
    bs[1]= line_box (decorate_middle (ip),
                     3*uw/2, hh, w-(3*uw/2), h-hh, pen);
    bs[2]= arc_box (decorate_middle (ip),
                    w- (2*uw), 0, w, 2*h, 240<<6, 360<<6, pen);
    return composite_box (ip, bs, xs, ys);
}
Ejemplo n.º 28
0
void kFoldData(uint k, const TrainingData& allData, std::vector<TrainingData>& foldTraining,
    std::vector<TestingData>& foldTesting)
{
  uint n = allData.x.rows();
  // assert(n == allData.u.rows());
  assert(n == allData.y.rows());
  uint dx = allData.x.cols();
  uint dy = allData.y.cols();
  uint du = allData.u.cols();
  uint priorSize = allData.u.rows();
  assert(dx == du);
  for (uint i=0; i<k; i++)
  {
    uint trainSize;
    uint testSize;
    ithFoldSizes(k,i,n,trainSize,testSize);
    Eigen::MatrixXd x(trainSize, dx);
    Eigen::MatrixXd xs(testSize, dx);
    Eigen::MatrixXd y(trainSize, dy);
    Eigen::MatrixXd ys(testSize, dy);
    Eigen::MatrixXd u = allData.u;
    fillSubset(k, i, allData.x, x, xs);
    fillSubset(k, i, allData.y, y, ys);
    Eigen::VectorXd lambda = Eigen::VectorXd::Ones(priorSize);
    lambda = lambda / double(priorSize);
    if (allData.xtp1.rows() > 0)
    {
      Eigen::MatrixXd xtp1(trainSize, dx);
      Eigen::MatrixXd xtp1s(testSize, dx);
      fillSubset(k, i, allData.xtp1, xtp1,xtp1s);
      foldTraining.push_back(TrainingData(u, lambda, x, y, xtp1)); 
    }
    else
    {
      foldTraining.push_back(TrainingData(u, lambda, x, y)); 
    }
    foldTesting.push_back(TestingData(xs, ys)); 
  }
}
Ejemplo n.º 29
0
/*
 * For converting param specs for Regions and LinkPolicies
 */
ValueMap toValueMap(const char* yamlstring,
                    Collection<ParameterSpec>& parameters,
                    const std::string & nodeType,
                    const std::string & regionName)
{

    ValueMap vm;

    // yaml-cpp bug: append a space if it is only one character
    // This is very inefficient, but should be ok since it is
    // just used at construction time for short strings
    std::string paddedstring(yamlstring);
    // TODO: strip white space to determine if empty
    bool empty = (paddedstring.size() == 0);

    if (paddedstring.size() < 2)
        paddedstring = paddedstring + " ";
    std::stringstream s(paddedstring);
    // IMemStream s(yamlstring, ::strlen(yamlstring));

    // TODO: utf-8 compatible?
    YAML::Node doc;
    if (!empty)
    {
        YAML::Parser parser(s);
        bool success = parser.GetNextDocument(doc);

        if (!success)
            NTA_THROW << "Unable to find document in YAML string";

        // A ValueMap is specified as a dictionary
        if (doc.Type() != YAML::NodeType::Map)
        {
            std::string ys(yamlstring);
            if (ys.size() > 30)
            {
                ys = ys.substr(0, 30) + "...";
            }
            NTA_THROW << "YAML string '" << ys
                      << "' does not not specify a dictionary of key-value pairs. "
                      << "Region and Link parameters must be specified at a dictionary";
        }
    }

    // Grab each value out of the YAML dictionary and put into the ValueMap
    // if it is allowed by the nodespec.
    YAML::Iterator i;
    for (i = doc.begin(); i != doc.end(); i++)
    {
        const std::string key = i.first().to<std::string>();
        if (!parameters.contains(key))
        {
            std::stringstream ss;
            for (UInt j = 0; j < parameters.getCount(); j++)
            {
                ss << "   " << parameters.getByIndex(j).first << "\n";
            }

            if (nodeType == std::string(""))
            {
                NTA_THROW << "Unknown parameter '" << key << "'\n"
                          << "Valid parameters are:\n" << ss.str();
            }
            else
            {
                NTA_CHECK(regionName != std::string(""));
                NTA_THROW << "Unknown parameter '" << key << "' for region '"
                          << regionName << "' of type '" << nodeType << "'\n"
                          << "Valid parameters are:\n" << ss.str();
            }
        }
        if (vm.contains(key))
            NTA_THROW << "Parameter '" << key << "' specified more than once in YAML document";
        ParameterSpec spec = parameters.getByName(key);
        try
        {
            Value v = toValue(i.second(), spec.dataType);
            if (v.isScalar() && spec.count != 1)
            {
                throw std::runtime_error("Expected array value but got scalar value");
            }
            if (!v.isScalar() && spec.count == 1)
            {
                throw std::runtime_error("Expected scalar value but got array value");
            }
            vm.add(key, v);
        } catch (std::runtime_error& e) {
            NTA_THROW << "Unable to set parameter '" << key << "'. " << e.what();
        }
    }

    // Populate ValueMap with default values if they were not specified in the YAML dictionary.
    for (size_t i = 0; i < parameters.getCount(); i++)
    {
        std::pair<std::string, ParameterSpec>& item = parameters.getByIndex(i);
        if (!vm.contains(item.first))
        {
            ParameterSpec & ps = item.second;
            if (ps.defaultValue != "")
            {
                // TODO: This check should be uncommented after dropping NuPIC 1.x nodes (which don't comply)
                // if (ps.accessMode != ParameterSpec::CreateAccess)
                // {
                //   NTA_THROW << "Default value for non-create parameter: " << item.first;
                // }

                try {
#ifdef YAMLDEBUG
                    NTA_DEBUG << "Adding default value '" << ps.defaultValue
                              << "' to parameter " << item.first
                              << " of type " << BasicType::getName(ps.dataType)
                              << " count " << ps.count;
#endif
                    Value v = toValue(ps.defaultValue, ps.dataType);
                    vm.add(item.first, v);
                } catch (...) {
                    NTA_THROW << "Unable to set default value for item '"
                              << item.first << "' of datatype "
                              << BasicType::getName(ps.dataType)
                              <<" with value '" << ps.defaultValue << "'";
                }
            }
        }
    }

    return vm;
}
Ejemplo n.º 30
0
void sfml_loop(Snake &snake) {
  sf::Texture texture;
  texture.loadFromMemory(snake.get_raw_img(), snake.get_raw_img_size());
  sf::RenderWindow window({ texture.getSize().x, texture.getSize().y },
                          "Snakes & Flies",
                          sf::Style::Titlebar | sf::Style::Close);
  window.setVerticalSyncEnabled(true);

  sf::Sprite sprite;
  sprite.setTexture(texture);

  unsigned long snake_size = 0;
  std::vector<double> xs(snake_size), ys(snake_size);

  bool inited = false, play = false;
  std::vector<sf::Vertex> snake_scheme;
  snake_scheme.push_back(sf::Vertex({ 0, 0 }, sf::Color::Red));

  while (window.isOpen()) {
    // check all the window's events that were triggered since the last
    // iteration of the loop
    sf::Event event;
    while (window.pollEvent(event)) {
      if (event.type == sf::Event::Closed) {
        window.close();
      }

      if (event.type == sf::Event::MouseMoved) {
        if (!inited) {
          snake_scheme.back().position =
              sf::Vector2f(sf::Mouse::getPosition(window));
        }
      }

      if (event.type == sf::Event::MouseButtonPressed) {
        if (!inited) {
          snake_scheme.insert(
              snake_scheme.end() - 1,
              sf::Vertex(sf::Vector2f(sf::Mouse::getPosition(window)),
                         sf::Color::Red));
        }
      }

      if (event.type == sf::Event::KeyPressed) {
        if (event.key.code == sf::Keyboard::Escape) {
          window.close();
        }
        if (event.key.code == sf::Keyboard::Space) {
          play = !play;
        }
        if (event.key.code == sf::Keyboard::Left ||
            event.key.code == sf::Keyboard::Right) {
          bool direction = event.key.code == sf::Keyboard::Right;
          if (!snake.shift_frame(direction)) {
            window.close();
          }
          texture.loadFromMemory(snake.get_raw_img(), snake.get_raw_img_size());
        }
      }

      if (event.type == sf::Event::KeyPressed && snake_scheme.size() > 2) {
        if (!inited) {
          if (snake.is_closed()) {
            snake_scheme.back() = snake_scheme.front();
          } else {
            snake_scheme.pop_back();
          }

          int implicit_joints = snake.get_implicit();

          if (implicit_joints > 0) {
            snake_size = implicit_joints * (snake_scheme.size() - 1) + 1;
          } else {
            snake_size = snake_scheme.size();
          }
          xs.resize(snake_size);
          ys.resize(snake_size);

          if (implicit_joints > 0) {
            for (int k = 0; k < snake_scheme.size() - 1; ++k) {
              auto x_diff = (snake_scheme[k + 1].position.x -
                             snake_scheme[k].position.x) /
                            implicit_joints;
              auto y_diff = (snake_scheme[k + 1].position.y -
                             snake_scheme[k].position.y) /
                            implicit_joints;
              for (int j = 0; j < implicit_joints; ++j) {
                xs[k * snake.get_implicit() + j] =
                    snake_scheme[k].position.x + j * x_diff;
                ys[k * snake.get_implicit() + j] =
                    snake_scheme[k].position.y + j * y_diff;
              }
            }
          }
          xs.back() = snake_scheme[snake_scheme.size() - 1].position.x;
          ys.back() = snake_scheme[snake_scheme.size() - 1].position.y;
          snake_scheme.resize(snake_size, { { 0, 0 }, sf::Color::Red });
          snake.set_xs(xs);
          snake.set_ys(ys);
          snake.set_pentamat();
        }
        inited = true;
      }
    }

    if (inited && play) {
      bool local_minima = snake.update();
      if (local_minima) {
        window.close();
      }
      xs = snake.get_xs();
      ys = snake.get_ys();
      for (int k = 0; k < snake_size; ++k) {
        snake_scheme[k].position.x = xs[k];
        snake_scheme[k].position.y = ys[k];
      }
    }

    window.draw(sprite);
    window.draw(&snake_scheme[0], (unsigned)snake_scheme.size(),
                sf::LinesStrip);

    window.display();
  }
}