Пример #1
0
void PFilter<N>::resample() {
	Particle<N> new_particles[PARTICLES];
	boost::mt19937 rng(time(0));
	boost::uniform_int<> rdist(0, 1000);
	double r = (1.0 / PARTICLES) * ((double)rdist(rng)) / 1000.0;
	double c = particles[0].weight;
	int i = 1;
	for (int j = 0; j < PARTICLES; ++j) {
		double u = r + ((double)j) * (1.0 / PARTICLES);
		while (u > c) {
			i = (i + 1) % PARTICLES;
			c += particles[i].weight;
		}
		new_particles[j] = particles[i];
	}
	total_w = 0.0;
	for (i = 0; i < PARTICLES; ++i) {
		particles[i] = new_particles[i];
		total_w += particles[i].weight;
	}
	fit = total_w;
	// Re-normalize
	double total_w_bu = 0.0;
	for (int i = 0; i < PARTICLES; ++i) {
		particles[i].weight /= total_w;
		total_w_bu += particles[i].weight;
	}
	total_w = total_w_bu;
}
Пример #2
0
void Randn<T>::forward_impl(const Variables &inputs, const Variables &outputs) {
  std::normal_distribution<T> rdist(mu_, sigma_);
  T *y = outputs[0]->cast_data_and_get_pointer<T>(this->ctx_);
  for (int s = 0; s < outputs[0]->size(); s++) {
    y[s] = rdist(rgen_);
  }
}
Пример #3
0
int main() {
    RNGType rng;
    boost::normal_distribution<> rdist(1.0,0.5); /**< normal distribution
                           with mean of 1.0 and standard deviation of 0.5 */

    boost::variate_generator< RNGType, boost::normal_distribution<> >
                    get_rand(rng, rdist);

    std::vector<double> v(1000);
    generate(v.begin(),v.end(),get_rand);
    return 0;
}
void test_zono_volume(int n, int m, NT tolerance = 0.15)
{
    typedef Cartesian<NT>    Kernel;
    typedef typename Kernel::Point    Point;
    typedef boost::mt19937    RNGType;
    typedef Zonotope<Point> Zonotope;
    Zonotope ZP = gen_zonotope<Zonotope, RNGType>(n, m);

    // Setup the parameters
    int walk_len=1;
    int nexp=1, n_threads=1;
    NT e=0.1, err=0.0000000001;
    NT C=2.0,ratio,frac=0.1,delta=-1.0, round_value = 1.0;
    int rnum = std::pow(e,-2) * 400 * n * std::log(n);
    int N = 500 * ((int) C) + ((int) (n * n / 2));
    int W = 4*n*n+500;
    ratio = 1.0-1.0/(NT(n));
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    RNGType rng(seed);
    boost::normal_distribution<> rdist(0,1);
    boost::random::uniform_real_distribution<>(urdist);
    boost::random::uniform_real_distribution<> urdist1(-1,1);
    std::pair<NT,NT> res_round;

    vars<NT, RNGType> var(rnum,n,walk_len,n_threads,err,e,0,0,0,0,rng,
                          urdist,urdist1,-1.0,false,false,false,false,false,false,true,false);

    //Compute chebychev ball//
    std::pair<Point,NT> CheBall;
    CheBall = ZP.ComputeInnerBall();

    // Estimate the volume
    std::cout << "--- Testing volume of Zonotope in dimension: " << n <<" and number of generators: "<< m << std::endl;
    std::cout << "Number type: " << typeid(NT).name() << std::endl;
    NT vol_exact = exact_zonotope_vol<NT>(ZP);
    res_round = rounding_min_ellipsoid(ZP, CheBall, var);
    round_value = round_value * res_round.first;
    NT vol = 0;
    unsigned int const num_of_exp = 10;
    for (unsigned int i=0; i<num_of_exp; i++)
    {
        CheBall = ZP.ComputeInnerBall();
        vars<NT, RNGType> var2(rnum,n,10 + n/10,n_threads,err,e,0,0,0,0,rng,
                               urdist,urdist1,-1.0,false,false,false,false,false,false,true,false);
        vars_g<NT, RNGType> var1(n,walk_len,N,W,1,e,CheBall.second,rng,C,frac,ratio,delta,false,
                                 false,false,false,false,false,false,true,false);
        vol += round_value * volume_gaussian_annealing(ZP, var1, var2, CheBall);
    }
    NT error = std::abs(((vol/num_of_exp)-vol_exact))/vol_exact;
    std::cout << "Computed volume (average) = " << vol/num_of_exp << std::endl;
    std::cout << "Expected volume = " << vol_exact << std::endl;
            CHECK(error < tolerance);
}
Пример #5
0
int main(int, char**)
{
    binary_tree<int> tree;

    // populate tree
    std::default_random_engine reng;
    reng.seed();
    std::uniform_int_distribution<int> rdist(0, 100);

    for(int i = 0; i < 10; i++)
    {
        tree.insert(rdist(reng));
    }

    // generator does not work with std algorithms nowm is not a valid iterator
    /*
    std::cout << "Tree traversed pre-order: " << std::endl;
    std::copy(tree.pre_order(), crs::generator<int>(), std::ostream_iterator<int>(std::cout, " ,"));
    std::cout << std::endl;

    std::cout << "Tree traversed in-order: " << std::endl;
    std::copy(tree.in_order(), crs::generator<int>(), std::ostream_iterator<int>(std::cout, " ,"));
    std::cout << std::endl;
    */

    crs::generator<int> io = tree.in_order();
    crs::generator<int> po = tree.pre_order();

    std::cout << "Tree traversal result:" << std::endl;
    std::cout << "pre-order\tin-order" << std::endl;

    for(; po != crs::generator<int>(); ++po, ++io)
    {
        std::cout << *po << "\t\t" << *io << std::endl;
    }
}
void test_CV_volume(Polytope &HP, NT expected, NT tolerance=0.3)
{

    typedef typename Polytope::PolytopePoint Point;

    // Setup the parameters
    int n = HP.dimension();
    int walk_len=1;
    int nexp=1, n_threads=1;
    NT e=0.1, err=0.0000000001;
    NT C=2.0,ratio,frac=0.1,delta=-1.0;
    int rnum = std::pow(e,-2) * 400 * n * std::log(n);
    int N = 500 * ((int) C) + ((int) (n * n / 2));
    int W = 4*n*n+500;
    ratio = 1.0-1.0/(NT(n));
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    RNGType rng(seed);
    boost::normal_distribution<> rdist(0,1);
    boost::random::uniform_real_distribution<>(urdist);
    boost::random::uniform_real_distribution<> urdist1(-1,1);

    //compute the chebychev ball
    std::pair<Point,NT> CheBall;


    // Estimate the volume
    std::cout << "Number type: " << typeid(NT).name() << std::endl;
    NT vol = 0;
    unsigned int const num_of_exp = 15;
    for (unsigned int i=0; i<num_of_exp; i++)
    {
        CheBall = HP.ComputeInnerBall();
        vars<NT, RNGType> var2(rnum,n,10 + n/10,n_threads,err,e,0,0,0,0,rng,
                 urdist,urdist1,-1.0,false,false,false,false,false,false,true,false);
        vars_g<NT, RNGType> var1(n,walk_len,N,W,1,e,CheBall.second,rng,C,frac,ratio,delta,false,
                    false,false,false,false,false,false,true,false);
        vol += volume_gaussian_annealing(HP, var1, var2, CheBall);
    }
    NT error = std::abs(((vol/num_of_exp)-expected))/expected;
    std::cout << "Computed volume (average) = " << vol/num_of_exp << std::endl;
    std::cout << "Expected volume = " << expected << std::endl;
            CHECK(error < tolerance);
}
void CPPMSimulationDataGenerator::Pulse()
{
    std::transform(pulses.begin(), pulses.end(), pulses.begin(), [&](double x) {
            double by = 10*rdist(rgen)*(rgen()&1?1:-1);
            return (x+by > 2000 || x+by < 1000) ? x-by : x+by;
        });

    mCPPMSimulationData.Advance(mClockGenerator.AdvanceByTimeS(.005));
    mCPPMSimulationData.Transition();

    std::for_each(pulses.begin(), pulses.end(), [&](double pulseLen) {
            mCPPMSimulationData.Advance(mClockGenerator.AdvanceByTimeS(.0003));
            mCPPMSimulationData.Transition();
            mCPPMSimulationData.Advance(mClockGenerator.AdvanceByTimeS((pulseLen * 1E-6) - 0.0003));
            mCPPMSimulationData.Transition();
        });
    mCPPMSimulationData.Advance(mClockGenerator.AdvanceByTimeS(.0003));
    mCPPMSimulationData.Transition();
}
Пример #8
0
void minmaxrad (float xmin, float xmax, float ymin, float ymax, float a[],
						float *minr, float *maxr)
{
    int i;
    float rd[5];
    float cdist (float x, float y, float a[]), near;

    rd[1] = rdist (xmin, ymax, a);
    rd[2] = rdist (xmin, ymin, a);
    rd[3] = rdist (xmax, ymin, a);
    rd[4] = rdist (xmax, ymax, a);

    *minr = 1.e6;
    *maxr = 0;

    /* If the integration box doesn't cross the x or y-axis centered on
       the object... */

    for (i=1; i <= 4; i++) {
        if (rd[i] < *minr) *minr = rd[i];
        if (rd[i] > *maxr) *maxr = rd[i];
    };

    /* But if the integration box does cross the x or y-axis centered on
       the object... */

    if ((a[1] < xmax && a[1] > xmin)) {
        if (ymax - a[2] < 0.) 
	    near = ymax;
        else
            near = ymin;
        *minr = rdist (a[1], near, a);
    };

    if ((a[2] < ymax && a[2] > ymin)) {
        if (xmax - a[1] < 0.) 
	    near = xmax;
        else
            near = xmin;
        *minr = rdist (near, a[2], a);
    }

    /* If the center is on the border of the integration box */

    if (a[1] < xmax && a[1] > xmin && (a[2] == ymin || a[2] == ymax)) *minr=0;
    if (a[2] < ymax && a[2] > ymin && (a[1] == xmin || a[1] == xmax)) *minr=0;

}
U32 PWMSimulationDataGenerator::GenerateSimulationData(U64 largest_sample_requested,
                                                       U32 sample_rate,
                                                       SimulationChannelDescriptor **simulation_channel)
{
    U64 adjusted_largest_sample_requested = AnalyzerHelpers::AdjustSimulationTargetSample(largest_sample_requested,
                                            sample_rate,
                                            mSimulationSampleRateHz);

    while (mPWMSimulationData.GetCurrentSampleNumber() < adjusted_largest_sample_requested) {
        double by = 10*rdist(rgen)*(rgen()&1?1:-1);
        pulseLen += (pulseLen+by > 2000 || pulseLen+by < 1000) ? -by : by;

        mPWMSimulationData.Advance(mSimulationSampleRateHz / 50);

        mPWMSimulationData.TransitionIfNeeded(BIT_HIGH);
        mPWMSimulationData.Advance(mClockGenerator.AdvanceByTimeS(pulseLen * 1E-6));
        mPWMSimulationData.TransitionIfNeeded(BIT_LOW);
    }

    *simulation_channel = &mPWMSimulationData;
    return 1;
}
void rounding_test(Polytope &P, bool rot, NT expected, NT tolerance=0.2)
{

    typedef typename Polytope::PolytopePoint Point;

    // Setup the parameters
    int n = P.dimension();
    int walk_len=10 + n/10;
    int nexp=1, n_threads=1;
    NT e=1, err=0.0000000001;
    int rnum = std::pow(e,-2) * 400 * n * std::log(n);
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    RNGType rng(seed);
    boost::normal_distribution<> rdist(0,1);
    boost::random::uniform_real_distribution<>(urdist);
    boost::random::uniform_real_distribution<> urdist1(-1,1);
    vars<NT, RNGType> var(rnum,n,walk_len,n_threads,err,e,0,0,0,0,rng,
             urdist,urdist1,-1.0,false,false,false,false,false,false,true,false);

    std::cout << "Number type: " << typeid(NT).name() << std::endl;
    //apply rotation if requested
    NT rot_val;
    if(rot){
        std::cout << "\n--- Rotation is ON "<< std::endl;
        rot_val = rotating<NT>(P);
        std::cout << "Rotation value = "<<rot_val<<std::endl;
    }
    std::pair<Point,NT> CheBall;
    Point c;
    NT radius;
    NT round_value=1.0, ratio1,ratio2;
    std::pair<NT,NT> res_round;
    double tstart1 = (double)clock()/(double)CLOCKS_PER_SEC;
    int count=1;
    //Compute chebychev ball//
    CheBall = P.ComputeInnerBall();

    //apply rounding
    res_round = rounding_min_ellipsoid(P, CheBall, var);
    round_value = round_value * res_round.first;
    ratio2 = res_round.second;
    ratio1 = 0.0;
    //apply rounding until conditios are satisfied
    while(ratio2>ratio1 && count<=1) {
        CheBall = P.ComputeInnerBall(); //compute the new chebychev center
        res_round = rounding_min_ellipsoid(P, CheBall, var);
        round_value = round_value * res_round.first;
        ratio1=ratio2;
        ratio2 = res_round.second;
        count++;
    }
    double tstop1 = (double)clock()/(double)CLOCKS_PER_SEC;
    std::cout<<"\nround value is: "<<round_value<<std::endl;
    std::cout << "Rounding time = " << tstop1 - tstart1 << std::endl;
    CheBall = P.ComputeInnerBall(); //compute the new chebychev center

    //estimate volume
    NT vol = 0;
    unsigned int const num_of_exp = 10;
    for (unsigned int i=0; i<num_of_exp; i++)
    {
        vol += round_value*volume(P,var,CheBall);
    }
    NT error = std::abs(((vol/num_of_exp)-expected))/expected;
    std::cout << "Computed volume (average) = " << vol/num_of_exp << std::endl;
    std::cout << "Expected volume = " << expected << std::endl;
    CHECK(error < tolerance);

}
Пример #11
0
__stdcall unsigned int master_proto (void* _args) {
	master_proto_args args = *reinterpret_cast<master_proto_args*> (_args);

	PostMessage (args.hwnd, qm_master_begin, args.id, 0);

	std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> lookup (nullptr, freeaddrinfo);
	{
		std::default_random_engine reng (std::chrono::system_clock::now ().time_since_epoch ().count ());
		std::uniform_int_distribution<> rdist (0, 19);
		std::ostringstream host;
		host << "arma2oapc.ms" << rdist (reng) << ".gamespy.com";

		addrinfo hints = addrinfo ();
		hints.ai_family = AF_INET;
		hints.ai_socktype = SOCK_STREAM;
		hints.ai_protocol = IPPROTO_TCP;
		addrinfo* tmp;
		int r = getaddrinfo (host.str ().c_str (), "28910", &hints, &tmp); // TODO load balance
		if (r) {
			SendMessage (args.hwnd, qm_master_error, args.id, reinterpret_cast<LPARAM> (wstrerror (WSAGetLastError ()).c_str ()));
			return 0;
		}
		lookup.reset (tmp);
	}

	qsocket socket {lookup->ai_family, lookup->ai_socktype, lookup->ai_protocol};
	if (socket == INVALID_SOCKET) {
		SendMessage (args.hwnd, qm_master_error, args.id, reinterpret_cast<LPARAM> (wstrerror (WSAGetLastError ()).c_str ()));
		return 0;
	}

	int r = connect (socket, lookup->ai_addr, lookup->ai_addrlen);
	if (r == SOCKET_ERROR) {
		SendMessage (args.hwnd, qm_master_error, args.id, reinterpret_cast<LPARAM> (wstrerror (WSAGetLastError ()).c_str ()));
		return 0;
	}

	// transmit request
	std::array<unsigned char, 9> master_validate;
	enctypex_decoder_rand_validate (&master_validate[0]);
	{
		std::ostringstream packet;
		packet << '\0'
			   << '\1'
			   << '\3'
			   << '\0' // 32-bit
			   << '\0'
			   << '\0'
			   << '\0'
			   << "arma2oapc" << '\0'
			   << "gslive" << '\0';
		std::copy (master_validate.begin (), master_validate.end () - 1, std::ostreambuf_iterator<char> (packet)); // note: don't copy the final '\0' byte of master_validate
		packet << "" << '\0' // filter (note, not preceeded by a '\0' separator either
			   << REQUEST << '\0'
			   << '\0'
			   << '\0'
			   << '\0'
			   << '\1'; // 1 = requested information
		std::vector<char> buf (2 + packet.str ().size ());
		WSAHtons (socket, buf.size (), reinterpret_cast<u_short*> (&buf[0]));
		const std::string s = packet.str ();
		std::copy (s.begin (), s.end (), 2 + buf.begin ());

		int r = send (socket, &buf[0], buf.size (), 0);
		if (r == SOCKET_ERROR) {
			SendMessage (args.hwnd, qm_master_error, args.id, reinterpret_cast<LPARAM> (wstrerror (WSAGetLastError ()).c_str ()));
			return 0;
		} else if (r != static_cast<int> (buf.size ())) {
			PostMessage (args.hwnd, qm_master_error, args.id, reinterpret_cast<LPARAM> (L"short send"));
			return 0;
		}
	}
	shutdown (socket, SD_SEND); // XXX error check

	// read response
	enctypex_data_t enctypex_data;
	enctypex_data.start = 0;
	std::vector<unsigned char> data;
	data.reserve (16384);
	while (true) {
		std::array<char, 8192> buf;
		int r = recv (socket, &buf[0], buf.size (), 0);
		if (r == SOCKET_ERROR) {
			SendMessage (args.hwnd, qm_master_error, args.id, reinterpret_cast<LPARAM> (wstrerror (WSAGetLastError ()).c_str ()));
			return 0;
		} else if (r == 0) {
			PostMessage (args.hwnd, qm_master_error, args.id, reinterpret_cast<LPARAM> (L"short recv"));
			return 0;
		}
		std::copy (buf.begin (), buf.begin () + r, std::back_inserter (data));
		PostMessage (args.hwnd, qm_master_progress, args.id, data.size ());

		int len = data.size ();
		unsigned char* endp = enctypex_decoder (reinterpret_cast<unsigned char*> (const_cast<char*> ("Xn221z")), &master_validate[0], &data[0], &len, &enctypex_data);
		assert (endp);
		if (endp && enctypex_decoder_convert_to_ipport (endp, data.size () - (reinterpret_cast<unsigned char*> (endp) - &data[0]), nullptr, nullptr, 0, 0)) {
			break;
		}
	}
	shutdown (socket, SD_RECEIVE); // XXX handle errors

	static_assert (sizeof (server_endpoint) == 6, "server_endpoint is a weird size");
	{
		std::vector<server_endpoint> decoded_data (data.size () / 5); // XXX size seems like a bit of a guess!
		int len = enctypex_decoder_convert_to_ipport (&data[0] + enctypex_data.start, data.size () - enctypex_data.start, reinterpret_cast<unsigned char*> (decoded_data.data ()), nullptr, 0, 0);
		assert (len >= 0); // XXX handle (see gsmyfunc.h line 715)
		for (auto ep: decoded_data)
			SendMessage (args.hwnd, qm_master_found, args.id, reinterpret_cast<LPARAM> (&ep));
	}

	PostMessage (args.hwnd, qm_master_complete, args.id, 0);
	return 0;
}
Пример #12
0
static double ApproxEarthMoversMetric(
	vector<double>	&dd,
	int				wi,
	int				hi )
{
// find powers of 2 that are big enough

	int	w = CeilPow2( wi ),
		h = CeilPow2( hi );

	vector<double>	d( w*h, 0.0 );

	CopyRaster( &d[0], w, &dd[0], wi, wi, hi );

	UnnormHaarTf2D( d, w, h );

//	PrintVectorAsMat( stdout, d, 8 );

	vector<int>	cdist( w, 1 );
	vector<int>	rdist( h, 1 );
	int			mask;

	mask = w >> 1;  // only works for w = 2^n

	for( int x = 1; x < w; ++x ) {

		for( int tmp = x; !(tmp & mask); tmp <<= 1 )
			cdist[x] <<= 1;
	}

	mask = h >> 1;  // only works for h = 2^n

	for( int y = 1; y < h; ++y ) {

		for( int tmp = y; !(tmp & mask); tmp <<= 1 )
			rdist[y] <<= 1;
	}

// use of 1 as lower bound is right;
// do not care about sums, only differences

	double	approx = 0.0;  // approximate Earth Mover's metric

	for( int x = 1; x < w; ++x ) {

		for( int y = 1; y < h; ++y ) {

			int		dx		= cdist[x];
			int		dy		= rdist[y];
			double	dist	= min( dx, dy );

			if( dist < 0 ) {

				printf(
				"x %d, y %d, dx %d, dy %d, dist %f, d[x+w*y] %f\n",
				x, y, dx, dy, dist, d[x + w*y] );
			}

			approx += dist * abs( d[x + w*y] );
		}
	}

// this should never happen

	if( approx < 0 ) {

		printf(
		"##Negative metric?  wi=%d, hi=%d"
		"\nColumn dists: ", wi, hi );

		for( int x = 1; x < w; ++x )
			printf( "%d ", cdist[x] );

		printf( "\nRow dists: " );

		for( int y = 1; y < h; ++y )
			printf( "%d ", rdist[y] );

		printf( "\n" );

		exit( 42 );
	}

// Normalize:
// - divide by 2 deltas per move unit.
// - divide by N pixels (per pixel cost).
// - divide by Poisson noise on area N.

	int		N = wi * hi;

	approx /= 2.0 * N * sqrt( N );

	printf(
	"Approximate EM metric %f for %d points.\n",
	approx, N );

	return approx;
}