コード例 #1
0
ファイル: randomshapetest.c プロジェクト: m1ch4ls/gfxprim
void draw_random_rectangle(GP_Pixel pixel)
{
	int x0, y0, x1, y1;
	random_point(win->context, &x0, &y0);
	random_point(win->context, &x1, &y1);

	if (fill_flag)
		GP_FillRect(win->context, x0, y0, x1, y1, pixel);

	if (outline_flag)
		GP_Rect(win->context, x0, y0, x1, y1, white);
}
コード例 #2
0
ファイル: randomshapetest.c プロジェクト: m1ch4ls/gfxprim
void draw_random_triangle(GP_Pixel pixel)
{
	int x0, y0, x1, y1, x2, y2;
	random_point(win->context, &x0, &y0);
	random_point(win->context, &x1, &y1);
	random_point(win->context, &x2, &y2);

	if (fill_flag)
		GP_FillTriangle(win->context, x0, y0, x1, y1, x2, y2, pixel);

	if (outline_flag)
		GP_Triangle(win->context, x0, y0, x1, y1, x2, y2, white);
}
コード例 #3
0
ファイル: randomshapetest.c プロジェクト: m1ch4ls/gfxprim
void draw_random_tetragon(GP_Pixel pixel)
{
	int x0, y0, x1, y1, x2, y2, x3, y3;
	random_point(win->context, &x0, &y0);
	random_point(win->context, &x1, &y1);
	random_point(win->context, &x2, &y2);
	random_point(win->context, &x3, &y3);

	if (fill_flag)
		GP_FillTetragon(win->context, x0, y0, x1, y1, x2, y2, x3, y3, pixel);

	if (outline_flag)
		GP_Tetragon(win->context, x0, y0, x1, y1, x2, y2, x3, y3, pixel);
}
コード例 #4
0
ファイル: lattice_point_gen.cpp プロジェクト: honr/shawn
   // ----------------------------------------------------------------------
   bool
   LatticePointGenerator::
   generate_point( shawn::Vec& v )
      throw()
   {
//	   ++mycount;
//	   cout << "Calling generate point" << mycount << endl;
	  if( check_fail_count_ ) fail_count_=0;
      while(1) {
		  if (box().lower().z()+cur_z_*spacing_>box().upper().z()) {
//				cout << "returned false" << endl;		
			  return false;
		  }
         v=random_point();
		 if( make_feasible(v) ) {
			return true;
		 }
         if( check_fail_count_ && (fail_count_<WARN_FAIL_COUNT) )
            if( ++fail_count_ == WARN_FAIL_COUNT ) {
               WARN( logger(),
                     "generated " << WARN_FAIL_COUNT 
                     << " points without a single hit: misconfiguration?" );
            }
      }
      return false;//cannot be reached
   }
コード例 #5
0
ファイル: benchmarks.cpp プロジェクト: FMX/CGAL
void Scene::bench_distance(Facet_tree& tree,
                           const int function,
                           const double duration)
{

    // generates 100K random point queries
    srand(0);
    unsigned int nb_queries = 100000;
    std::vector<Point> queries;
    for(unsigned int i=0;i<nb_queries;i++)
        queries.push_back(random_point(tree.bbox()));

    CGAL::Timer timer;
    timer.start();
    unsigned int nb = 0;
    while(timer.time() < duration)
    {
        const Point& query = queries[nb%nb_queries];
        switch(function)
        {
        case SQ_DISTANCE:
            tree.squared_distance(query);
            break;
        case CLOSEST_POINT:
            tree.closest_point(query);
            break;
        case CLOSEST_POINT_AND_PRIMITIVE_ID:
            tree.closest_point_and_primitive(query);
        }
        nb++;
    }

    double speed = (double)nb / (double)timer.time();
    std::cout << speed << " queries/s" << std::endl;
}
コード例 #6
0
static void randomize_params(size_t count, size_t maxVertex, SkScalar min, SkScalar max,
                             SkRandom* random, SkTArray<SkPoint>* positions,
                             SkTArray<SkPoint>* texCoords, bool hasTexCoords,
                             SkTArray<uint32_t>* colors, bool hasColors,
                             SkTArray<uint16_t>* indices, bool hasIndices) {
    for (uint32_t v = 0; v < count; v++) {
        positions->push_back(random_point(random, min, max));
        if (hasTexCoords) {
            texCoords->push_back(random_point(random, min, max));
        }
        if (hasColors) {
            colors->push_back(GrRandomColor(random));
        }
        if (hasIndices) {
            SkASSERT(maxVertex <= UINT16_MAX);
            indices->push_back(random->nextULessThan((uint16_t)maxVertex));
        }
    }
}
コード例 #7
0
ファイル: randomshapetest.c プロジェクト: m1ch4ls/gfxprim
void draw_random_polygon(GP_Pixel pixel)
{
	GP_Coord xy[10];
	int i;

	for (i = 0; i < 5; i++) {
		random_point(win->context, xy + 2*i, xy + 2*i + 1);
	}

	GP_FillPolygon_Raw(win->context, 5, xy, pixel);
}
コード例 #8
0
ファイル: randomshapetest.c プロジェクト: m1ch4ls/gfxprim
void draw_random_circle(GP_Pixel pixel)
{
	int x, y;
	random_point(win->context, &x, &y);
	int r = random() % 50;

	if (fill_flag)
		GP_FillCircle(win->context, x, y, r, pixel);

	if (outline_flag)
		GP_Circle(win->context, x, y, r, white);
}
コード例 #9
0
ファイル: Scene.cpp プロジェクト: weaselp/cgal
void Scene::generate_points_in(const unsigned int nb_points,
                               const double min,
                               const double max)
{
    if(m_pPolyhedron == NULL)
    {
        std::cout << "Load polyhedron first." << std::endl;
        return;
    }

    typedef CGAL::AABB_face_graph_triangle_primitive<Polyhedron> Primitive;
    typedef CGAL::AABB_traits<Kernel, Primitive> Traits;
    typedef CGAL::AABB_tree<Traits> Tree;

    std::cout << "Construct AABB tree...";
    Tree tree(faces(*m_pPolyhedron).first, faces(*m_pPolyhedron).second, *m_pPolyhedron);
    std::cout << "done." << std::endl;

    CGAL::Timer timer;
    timer.start();
    std::cout << "Generate " << nb_points << " points in interval ["
              << min << ";" << max << "]";

    unsigned int nb_trials = 0;
    Vector vec = random_vector();
    while(m_points.size() < nb_points)
    {
        Point p = random_point(tree.bbox());

        // measure distance
        FT signed_distance = std::sqrt(tree.squared_distance(p));

        // measure sign
        Ray ray(p,vec);
        int nb_intersections = (int)tree.number_of_intersected_primitives(ray);
        if(nb_intersections % 2 != 0)
            signed_distance *= -1.0;

        if(signed_distance >= min &&
                signed_distance <= max)
        {
            m_points.push_back(p);
            if(m_points.size()%(nb_points/10) == 0)
                std::cout << "."; // ASCII progress bar
        }
        nb_trials++;
    }
    double speed = (double)nb_trials / timer.time();
    std::cout << "done (" << nb_trials << " trials, "
              << timer.time() << " s, "
              << speed << " queries/s)" << std::endl;
    changed();
}
コード例 #10
0
ファイル: randomshapetest.c プロジェクト: m1ch4ls/gfxprim
void draw_random_ellipse(GP_Pixel pixel)
{
	int x, y;
	random_point(win->context, &x, &y);
	int rx = random() % 50;
	int ry = random() % 50;

	if (fill_flag)
		GP_FillEllipse(win->context, x, y, rx, ry, pixel);

	if (outline_flag)
		GP_Ellipse(win->context, x, y, rx, ry, white);
}
コード例 #11
0
point_t* sample_bright_points(const image_t* image, int n) {
    point_t* list = malloc(sizeof(point_t)*n);
    point_t p;
    int i=0;
    while(i<n) {
        p = random_point(image);
        if(pixel_get(image,p) > gsl_rng_uniform_int(image->r,1<<16)) {
            list[i++]=p;
            progress(i,n,"brights");
        }
    }
    return list;
}
コード例 #12
0
/*
 * [Step 1]
 * Here we compute the mean and standard deviation of the data;
 * but to avoid actually reading in all that data, we take a random
 * sample first.
 *
 * OBSOLETED by rejection sampling
 */
void compute_sd(const image_t* image, int sample_size, double* mean, double* sd) {
    unsigned short* sample;
    int i;

    sample = malloc(sizeof(unsigned short)*sample_size);

    //gsl_ran_sample(image->r, sample, sample_size, image->data, image->length/2, 2);
    for(i=0; i<sample_size; i++) {
        sample[i]=pixel_get(image,random_point(image));
        progress(i+1,sample_size,"samples");
    }

    *mean = gsl_stats_ushort_mean(sample, 1, sample_size);
    *sd = gsl_stats_ushort_sd_m(sample, 1, sample_size, *mean);
    free(sample);
}
コード例 #13
0
 // ----------------------------------------------------------------------
 bool
 RandomProcessPointGenerator::
 generate_point( shawn::Vec& v )
    throw()
 {
    if( check_fail_count_ ) fail_count_=0;
    while(1) {
       v=random_point();
       if( make_feasible(v) )
          return true;
       if( check_fail_count_ && (fail_count_<WARN_FAIL_COUNT) )
          if( ++fail_count_ == WARN_FAIL_COUNT ) {
             WARN( logger(),
                   "generated " << WARN_FAIL_COUNT 
                   << " points without a single hit: misconfiguration?" );
          }
    }
    return false;//cannot be reached
 }
コード例 #14
0
ファイル: benchmarks.cpp プロジェクト: FMX/CGAL
void Scene::bench_distances_vs_nbt()
{
    if(m_pPolyhedron == NULL)
    {
        std::cout << "Load polyhedron first." << std::endl;
        return;
    }

    std::cout << std::endl << "Benchmark distances against #triangles" << std::endl;
    std::cout << std::endl << "for random point queries and closest_point()" << std::endl;
    std::cout << "#Facets, #queries/s" << std::endl;

    // generates 10K random point queries
    const int nb_queries = 10000;
    std::vector<Point> queries;
    srand(0);
    for(int i=0;i<nb_queries;i++)
        queries.push_back(random_point(m_bbox));

    while(m_pPolyhedron->size_of_facets() < 1000000)
    {
        // refines mesh at increasing speed
        Refiner<Kernel,Polyhedron> refiner(m_pPolyhedron);
        std::size_t digits = nb_digits(m_pPolyhedron->size_of_facets());
        unsigned int nb_splits =
          static_cast<unsigned int>(0.2 * std::pow(10.0,(double)digits - 1.0));
        refiner.run_nb_splits(nb_splits);

        // constructs tree (out of timing)
        Facet_tree tree(m_pPolyhedron->facets_begin(),m_pPolyhedron->facets_end());
        tree.accelerate_distance_queries();

        // calls queries
        CGAL::Timer timer;
        timer.start();
        for(int i=0;i<nb_queries;i++)
            tree.closest_point(queries[i]);
        double duration = timer.time();
        int speed = (int)((double)nb_queries / (double)duration);

        std::cout << m_pPolyhedron->size_of_facets() << ", " << speed << std::endl;
    }
}
コード例 #15
0
ファイル: Scene.cpp プロジェクト: skyopener/OSCCAR-dev
void Scene::generate_inside_points(const unsigned int nb_points)
{
    if(m_pPolyhedron == NULL)
    {
        std::cout << "Load polyhedron first." << std::endl;
        return;
    }

    typedef CGAL::AABB_face_graph_triangle_primitive<Polyhedron> Primitive;
    typedef CGAL::AABB_traits<Kernel, Primitive> Traits;
    typedef CGAL::AABB_tree<Traits> Tree;

    std::cout << "Construct AABB tree...";
    Tree tree(m_pPolyhedron->facets_begin(),m_pPolyhedron->facets_end(),*m_pPolyhedron);
    std::cout << "done." << std::endl;

    CGAL::Timer timer;
    timer.start();
    std::cout << "Generate " << nb_points << " inside points";

    unsigned int nb_trials = 0;
    Vector vec = random_vector();
    while(m_points.size() < nb_points)
    {
        Point p = random_point(tree.bbox());
        Ray ray(p,vec);
        int nb_intersections = (int)tree.number_of_intersected_primitives(ray);
        if(nb_intersections % 2 != 0)
        {
            m_points.push_back(p);
            if(m_points.size()%(nb_points/10) == 0)
                std::cout << "."; // ASCII progress bar
        }
        nb_trials++;
    }
    double speed = (double)nb_trials / timer.time();
    std::cout << "done (" << nb_trials << " trials, "
              << timer.time() << " s, "
              << speed << " queries/s)" << std::endl;
}
コード例 #16
0
ファイル: poisson.c プロジェクト: morpheus-med/bart
int main_poisson(int argc, char* argv[])
{
	int yy = 128;
	int zz = 128;
	bool cutcorners = false;
	float vardensity = 0.;
	bool vd_def = false;
	int T = 1;
	int rnd = 0;
	bool msk = true;
	int points = -1;
	float mindist = 1. / 1.275;
	float yscale = 1.;
	float zscale = 1.;
	unsigned int calreg = 0;

	const struct opt_s opts[] = {

		OPT_INT('Y', &yy, "size", "size dimension 1"),
		OPT_INT('Z', &zz, "size", "size dimension 2"),
		OPT_FLOAT('y', &yscale, "acc", "acceleration dim 1"),
		OPT_FLOAT('z', &zscale, "acc", "acceleration dim 2"),
		OPT_UINT('C', &calreg, "size", "size of calibration region"),
		OPT_SET('v', &vd_def, "variable density"),
		OPT_FLOAT('V', &vardensity, "", "(variable density)"),
		OPT_SET('e', &cutcorners, "elliptical scanning"),
		OPT_FLOAT('D', &mindist, "", "()"),
		OPT_INT('T', &T, "", "()"),
		OPT_CLEAR('m', &msk, "()"),
		OPT_INT('R', &points, "", "()"),
	};

	cmdline(&argc, argv, 1, 1, usage_str, help_str, ARRAY_SIZE(opts), opts);

	if (vd_def && (0. == vardensity))
		vardensity = 20.;

	if (-1 != points)
		rnd = 1;


	assert((yscale >= 1.) && (zscale >= 1.));

	// compute mindest and scaling

	float kspext = MAX(yy, zz);

	int Pest = T * (int)(1.2 * powf(kspext, 2.) / (yscale * zscale));

	mindist /= kspext;
	yscale *= (float)kspext / (float)yy;
	zscale *= (float)kspext / (float)zz;

	if (vardensity != 0.) {

		// TODO
	}


	long dims[5] = { 1, yy, zz, T, 1 };
	complex float* mask = NULL;

	if (msk) {
		
		mask = create_cfl(argv[1], 5, dims);
		md_clear(5, dims, mask, sizeof(complex float));
	}

	int M = rnd ? (points + 1) : Pest;
	int P;
	
	while (true) {

		float (*points)[2] = xmalloc(M * sizeof(float[3]));

		int* kind = xmalloc(M * sizeof(int));
		kind[0] = 0;

		if (!rnd) {

			points[0][0] = 0.5;
			points[0][1] = 0.5;

			if (1 == T) {

				P = poissondisc(2, M, 1, vardensity, mindist, points);

			} else {

				float (*delta)[T] = xmalloc(T * T * sizeof(complex float));
				float dd[T];
				for (int i = 0; i < T; i++)
					dd[i] = mindist;

				mc_poisson_rmatrix(2, T, delta, dd);
				P = poissondisc_mc(2, T, M, 1, vardensity, (const float (*)[T])delta, points, kind);
			}

		} else { // random pattern

			P = M - 1;
			for (int i = 0; i < P; i++)
				random_point(2, points[i]);
		}

		if (P < M) {

			for (int i = 0; i < P; i++) {

				points[i][0] = (points[i][0] - 0.5) * yscale + 0.5;
				points[i][1] = (points[i][1] - 0.5) * zscale + 0.5;
			}

			// throw away points outside 
	
			float center[2] = { 0.5, 0.5 };

			int j = 0;
			for (int i = 0; i < P; i++) {

				if ((cutcorners ? dist : maxn)(2, center, points[i]) <= 0.5) {

					points[j][0] = points[i][0];
					points[j][1] = points[i][1];
					j++;
				}
			}

			P = j;


			if (msk) {

				// rethink module here
				for (int i = 0; i < P; i++) {

					int yy = (int)floorf(points[i][0] * dims[1]);
					int zz = (int)floorf(points[i][1] * dims[2]);

					if ((yy < 0) || (yy >= dims[1]) || (zz < 0) || (zz >= dims[2]))
						continue;

					if (1 == T)
					mask[zz * dims[1] + yy] = 1.;//cexpf(2.i * M_PI * (float)kind[i] / (float)T);
					else
					mask[(kind[i] * dims[2] + zz) * dims[1] + yy] = 1.;//cexpf(2.i * M_PI * (float)kind[i] / (float)T);
				}

			} else {

#if 1
				long sdims[2] = { 3, P };
				complex float* samples = create_cfl(argv[1], 2, sdims);
				for (int i = 0; i < P; i++) {

					samples[3 * i + 0] = 0.;
					samples[3 * i + 1] = (points[i][0] - 0.5) * dims[1];
					samples[3 * i + 2] = (points[i][1] - 0.5) * dims[2];
					//	printf("%f %f\n", creal(samples[3 * i + 0]), creal(samples[3 * i + 1]));
				}
				unmap_cfl(2, sdims, (void*)samples);
#endif
			}

			break;
		}

		// repeat with more points
		M *= 2;
		free(points);
		free(kind);
	}

	// calibration region

	assert((mask != NULL) || (0 == calreg));
	assert((calreg <= dims[1]) && (calreg <= dims[2]));

	for (unsigned int i = 0; i < calreg; i++) {
		for (unsigned int j = 0; j < calreg; j++) {

			int y = (dims[1] - calreg) / 2 + i;
			int z = (dims[2] - calreg) / 2 + j;

			for (int k = 0; k < T; k++) {

				if (0. == mask[(k * dims[2] + z) * dims[1] + y]) {

					mask[(k * dims[2] + z) * dims[1] + y] = 1.;
					P++;
				}
			}
		}
	}


	printf("points: %d", P);

	if (1 != T)
		printf(", classes: %d", T);

	if (NULL != mask) {

		float f = cutcorners ? (M_PI / 4.) : 1.;
		printf(", grid size: %ldx%ld%s = %ld (R = %f)", dims[1], dims[2], cutcorners ? "x(pi/4)" : "",
				(long)(f * dims[1] * dims[2]), f * T * dims[1] * dims[2] / (float)P);

		unmap_cfl(5, dims, (void*)mask);
	}

	printf("\n");
	exit(0);
}
コード例 #17
0
ファイル: Scene.cpp プロジェクト: skyopener/OSCCAR-dev
Plane Scene::random_plane(const CGAL::Bbox_3& bbox)
{
    Point p = random_point(bbox);
    Vector vec = random_vector();
    return Plane(p,vec);
}
コード例 #18
0
ファイル: Scene.cpp プロジェクト: skyopener/OSCCAR-dev
Segment Scene::random_segment(const CGAL::Bbox_3& bbox)
{
    Point p = random_point(bbox);
    Point q = random_point(bbox);
    return Segment(p,q);
}
コード例 #19
0
ファイル: Scene.cpp プロジェクト: skyopener/OSCCAR-dev
Line Scene::random_line(const CGAL::Bbox_3& bbox)
{
    Point p = random_point(bbox);
    Point q = random_point(bbox);
    return Line(p,q);
}
コード例 #20
0
ファイル: Scene.cpp プロジェクト: skyopener/OSCCAR-dev
Ray Scene::random_ray(const CGAL::Bbox_3& bbox)
{
    Point p = random_point(bbox);
    Point q = random_point(bbox);
    return Ray(p,q);
}
コード例 #21
0
ファイル: triangle.c プロジェクト: DorisGao/personal-uni
void display() {

	/* if i is 0 or 1, modulus breaks */
	int i = 2;
	float p[2] = {0, 0};
	float m[2] = {0, 0};

	glClear(GL_COLOR_BUFFER_BIT);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(-0.2, 1.2, -0.2, 1.2);

	glBegin(GL_POLYGON);
	/* Must set colour before each vertex, not before polygon */
	/* Maybe for the whole polygon? */
	/* Doesn't like glColor3i : use glColor3f instead */
		glColor3f(0.0, 1.0, 0.0);
		glVertex2f(0.0, 0.0);
		glVertex2f(1.0, 0.0);
		glVertex2f(0.5, 1.0);
	/* Pretty green triangle!! */
	glEnd();

	/* Generate one sane random place in the triangle */
	do {
		/* This +1 removes divide by 0 errors */
		p[0] = (float) 1 / ((rand() % i) + 1);
		p[1] = (float) 1 / ((rand() % i) + 1);

		i++;
	} while (check_point(p[0], p[1]) > 0);

	/* This becomes the start, from which we branch */
	i = 0;
	printf("final: %f, %f\n", p[0], p[1]);
	while(i < MAX_COUNT_STEPS) {

		switch(random_point()) {
			case 0:
			/* Point 0.0,0.0 */
				m[0] = p[0] / 2;
				m[1] = p[1] / 2;
				break;
			case 1:
			/* Point 0.5,1.0 */
				m[0] = ((0.5 - p[0]) / 2) + p[0];
				m[1] = ((1.0 - p[1]) / 2) + p[1];
				break;
			case 2:
			/* Point 1.0,0.0 */
				m[0] = ((1.0 - p[0]) / 2) + p[0];
				m[1] = p[1] / 2;
				break;
			default:
				printf("\nMassive error occurred, exiting\n");
				exit(1);
		}

		/* Fix typo */
		glBegin(GL_POINTS);
			glColor3f(1.0, 0.0, 0.0);
			glVertex2f(m[0], m[1]);
		glEnd();

		p[0] = m[0];
		p[1] = m[1];

		i++;
	}


	glFlush();
}
コード例 #22
0
ファイル: utils.c プロジェクト: coderodde/pathfinding.c
graph_data_t* create_random_graph(const size_t nodes, 
                                  size_t edges,
                                  const double maxx,
                                  const double maxy,
                                  const double maxz,
                                  const double max_distance)
{
    size_t i;
    char* p_name;

    directed_graph_node_t*              p_tail;
    directed_graph_node_t*              p_head;
    directed_graph_weight_function_t*   p_weight_function;
    unordered_map_t*                    p_point_map;
    point_3d_t*                         p_a;
    point_3d_t*                         p_b;
    graph_data_t*                       p_ret;
    double                              distance;
    
    p_ret = malloc(sizeof(*p_ret));

    if (!p_ret) return NULL;

    directed_graph_node_t** p_node_array = 
            malloc(sizeof(directed_graph_node_t*) * nodes);

    if (!p_ret) 
    {
        free(p_ret);
        return NULL;
    }

    if (!(p_weight_function = 
            directed_graph_weight_function_t_alloc(hash_function,
                                                   equals_function)))
    {
        free(p_ret);
        free(p_node_array);
        return NULL;
    }

    if (!(p_point_map = unordered_map_t_alloc(16, 
                                              1.0f, 
                                              hash_function,
                                              equals_function)))  
    {
        directed_graph_weight_function_t_free(p_weight_function);
        free(p_ret);
        free(p_node_array);
        return NULL;
    }

    for (i = 0; i < nodes; ++i) 
    {
        p_name = malloc(sizeof(char) * 20);
        sprintf(p_name, "%d", i);
        p_node_array[i] = directed_graph_node_t_alloc(p_name);
        unordered_map_t_put(p_point_map, 
                            p_node_array[i], 
                            random_point(maxx, maxy, maxz));
    }

    while (edges > 0)
    {
        p_tail = choose(p_node_array, nodes);
        p_head = choose(p_node_array, nodes);

        p_a = unordered_map_t_get(p_point_map, p_tail);
        p_b = unordered_map_t_get(p_point_map, p_head);

        distance = point_3d_t_distance(p_a, p_b);
        
        if (distance >= max_distance) 
        {
            continue;
        }
        
        directed_graph_node_t_add_arc(p_tail, p_head);

        directed_graph_weight_function_t_put(
                p_weight_function,
                p_tail,
                p_head,
                1.5 * distance);

        --edges;
    }

    p_ret->p_node_array      = p_node_array;
    p_ret->p_weight_function = p_weight_function;
    p_ret->p_point_map       = p_point_map;

    return p_ret;
}
コード例 #23
0
ファイル: vegas.c プロジェクト: Ayato-Harashima/CMVS-PMVS
int
gsl_monte_vegas_integrate (gsl_monte_function * f,
                           double xl[], double xu[],
                           size_t dim, size_t calls,
                           gsl_rng * r,
                           gsl_monte_vegas_state * state,
                           double *result, double *abserr)
{
  double cum_int, cum_sig;
  size_t i, k, it;

  if (dim != state->dim)
    {
      GSL_ERROR ("number of dimensions must match allocated size", GSL_EINVAL);
    }

  for (i = 0; i < dim; i++)
    {
      if (xu[i] <= xl[i])
        {
          GSL_ERROR ("xu must be greater than xl", GSL_EINVAL);
        }

      if (xu[i] - xl[i] > GSL_DBL_MAX)
        {
          GSL_ERROR ("Range of integration is too large, please rescale",
                     GSL_EINVAL);
        }
    }

  if (state->stage == 0)
    {
      init_grid (state, xl, xu, dim);

      if (state->verbose >= 0)
        {
          print_lim (state, xl, xu, dim);
        }
    }

  if (state->stage <= 1)
    {
      state->wtd_int_sum = 0;
      state->sum_wgts = 0;
      state->chi_sum = 0;
      state->it_num = 1;
      state->samples = 0;
      state->chisq = 0;
    }

  if (state->stage <= 2)
    {
      unsigned int bins = state->bins_max;
      unsigned int boxes = 1;

      if (state->mode != GSL_VEGAS_MODE_IMPORTANCE_ONLY)
        {
          /* shooting for 2 calls/box */

          boxes = floor (pow (calls / 2.0, 1.0 / dim));
          state->mode = GSL_VEGAS_MODE_IMPORTANCE;

          if (2 * boxes >= state->bins_max)
            {
              /* if bins/box < 2 */
              int box_per_bin = GSL_MAX (boxes / state->bins_max, 1);

              bins = GSL_MIN(boxes / box_per_bin, state->bins_max);
              boxes = box_per_bin * bins;

              state->mode = GSL_VEGAS_MODE_STRATIFIED;
            }
        }

      {
        double tot_boxes = gsl_pow_int ((double) boxes, dim);
        state->calls_per_box = GSL_MAX (calls / tot_boxes, 2);
        calls = state->calls_per_box * tot_boxes;
      }

      /* total volume of x-space/(avg num of calls/bin) */
      state->jac = state->vol * pow ((double) bins, (double) dim) / calls;

      state->boxes = boxes;

      /* If the number of bins changes from the previous invocation, bins
         are expanded or contracted accordingly, while preserving bin
         density */

      if (bins != state->bins)
        {
          resize_grid (state, bins);

          if (state->verbose > 1)
            {
              print_grid (state, dim);
            }
        }

      if (state->verbose >= 0)
        {
          print_head (state,
                      dim, calls, state->it_num, state->bins, state->boxes);
        }
    }

  state->it_start = state->it_num;

  cum_int = 0.0;
  cum_sig = 0.0;

  for (it = 0; it < state->iterations; it++)
    {
      double intgrl = 0.0, intgrl_sq = 0.0;
      double tss = 0.0;
      double wgt, var, sig;
      size_t calls_per_box = state->calls_per_box;
      double jacbin = state->jac;
      double *x = state->x;
      coord *bin = state->bin;

      state->it_num = state->it_start + it;

      reset_grid_values (state);
      init_box_coord (state, state->box);
      
      do
        {
          volatile double m = 0, q = 0;
          double f_sq_sum = 0.0;

          for (k = 0; k < calls_per_box; k++)
            {
              volatile double fval;
              double bin_vol;

              random_point (x, bin, &bin_vol, state->box, xl, xu, state, r);

              fval = jacbin * bin_vol * GSL_MONTE_FN_EVAL (f, x);

              /* recurrence for mean and variance (sum of squares) */

              {
                double d = fval - m;
                m += d / (k + 1.0);
                q += d * d * (k / (k + 1.0));
              }

              if (state->mode != GSL_VEGAS_MODE_STRATIFIED)
                {
                  double f_sq = fval * fval;
                  accumulate_distribution (state, bin, f_sq);
                }
            }

          intgrl += m * calls_per_box;

          f_sq_sum = q * calls_per_box;

          tss += f_sq_sum;

          if (state->mode == GSL_VEGAS_MODE_STRATIFIED)
            {
              accumulate_distribution (state, bin, f_sq_sum);
            }
        }
      while (change_box_coord (state, state->box));

      /* Compute final results for this iteration   */

      var = tss / (calls_per_box - 1.0)  ;

      if (var > 0) 
        {
          wgt = 1.0 / var;
        }
      else if (state->sum_wgts > 0) 
        {
          wgt = state->sum_wgts / state->samples;
        }
      else 
        {
          wgt = 0.0;
        }
        
     intgrl_sq = intgrl * intgrl;

     sig = sqrt (var);

     state->result = intgrl;
     state->sigma  = sig;

     if (wgt > 0.0)
       {
         double sum_wgts = state->sum_wgts;
         double wtd_int_sum = state->wtd_int_sum;
         double m = (sum_wgts > 0) ? (wtd_int_sum / sum_wgts) : 0;
         double q = intgrl - m;

         state->samples++ ;
         state->sum_wgts += wgt;
         state->wtd_int_sum += intgrl * wgt;
         state->chi_sum += intgrl_sq * wgt;

         cum_int = state->wtd_int_sum / state->sum_wgts;
         cum_sig = sqrt (1 / state->sum_wgts);

#if USE_ORIGINAL_CHISQ_FORMULA
/* This is the chisq formula from the original Lepage paper.  It
   computes the variance from <x^2> - <x>^2 and can suffer from
   catastrophic cancellations, e.g. returning negative chisq. */
         if (state->samples > 1)
           {
             state->chisq = (state->chi_sum - state->wtd_int_sum * cum_int) /
               (state->samples - 1.0);
           }
#else
/* The new formula below computes exactly the same quantity as above
   but using a stable recurrence */
         if (state->samples == 1) {
           state->chisq = 0;
         } else {
           state->chisq *= (state->samples - 2.0);
           state->chisq += (wgt / (1 + (wgt / sum_wgts))) * q * q;
           state->chisq /= (state->samples - 1.0);
         }
#endif
       }
     else
       {
         cum_int += (intgrl - cum_int) / (it + 1.0);
         cum_sig = 0.0;
       }         


      if (state->verbose >= 0)
        {
          print_res (state,
                     state->it_num, intgrl, sig, cum_int, cum_sig,
                     state->chisq);
          if (it + 1 == state->iterations && state->verbose > 0)
            {
              print_grid (state, dim);
            }
        }

      if (state->verbose > 1)
        {
          print_dist (state, dim);
        }

      refine_grid (state);

      if (state->verbose > 1)
        {
          print_grid (state, dim);
        }

    }

  /* By setting stage to 1 further calls will generate independent
     estimates based on the same grid, although it may be rebinned. */

  state->stage = 1;  

  *result = cum_int;
  *abserr = cum_sig;

  return GSL_SUCCESS;
}
コード例 #24
0
ファイル: main.cpp プロジェクト: BichengLUO/random_scene
int main(int argc, char *argv[])
{
	srand(time(NULL));
	if (argc != 9)
	{
		std::cout << usage << std::endl;
		return -1;
	}
	int nseg = atoi(argv[1]);
	int nray = atoi(argv[2]);
	int nline = atoi(argv[3]);
	int ncircle = atoi(argv[4]);

	double min = atof(argv[5]);
	double max = atof(argv[6]);
	bool integer = false;
	if (strcmp(argv[8], "int") == 0)
		integer = true;
	else if (strcmp(argv[8], "double") == 0)
		integer = false;
	else
	{
		std::cout << "Wrong output format!" << std::endl;
		return -1;
	}

	std::ofstream output(argv[7], std::ofstream::out);

	seg *segs = new seg[nseg];
	ray *rays = new ray[nray];
	line *lines = new line[nline];
	circle *circles = new circle[ncircle];

	for (int i = 0; i < nseg; i++)
	{
		segs[i].start = random_point(min, max);
		if (nseg > 8000)
			segs[i].end = near_random_point(segs[i].start, (max - min) * 0.014, (max - min) * 0.02);
		else
			segs[i].end = near_random_point(segs[i].start, (max - min) * 0.14, (max - min) * 0.2);
	}
	for (int i = 0; i < nray; i++)
	{
		rays[i].start = random_point(min, max);
		rays[i].dir = random_point(-max, max);
	}
	for (int i = 0; i < nline; i++)
	{
		lines[i].pos = random_point(min, max);
		lines[i].dir = random_point(-max, max);
	}
	for (int i = 0; i < ncircle; i++)
	{
		circles[i].center = random_point(min, max);
		point center = circles[i].center;
		double min_radius = (max - min) * 0.12;
		double max_radius = (max - min) * 0.15;
		double r = min_radius + randf() * (max_radius - min_radius);
		circles[i].radius = r;
	}

	output << nseg << " " << nray << " " << nline << " " << ncircle << std::endl;
	if (integer)
	{
		for (int i = 0; i < nseg; i++)
		{
			output << (int)round(segs[i].start.x) << " " << (int)round(segs[i].start.y) << " "
				<< (int)round(segs[i].end.x) << " " << (int)round(segs[i].end.y) << std::endl;
		}
		for (int i = 0; i < nray; i++)
		{
			output << (int)round(rays[i].start.x) << " " << (int)round(rays[i].start.y) << " "
				<< (int)round(rays[i].start.x + rays[i].dir.x) << " "
				<< (int)round(rays[i].start.y + rays[i].dir.y) << std::endl;
		}
		for (int i = 0; i < nline; i++)
		{
			output << (int)round(lines[i].pos.x) << " " << (int)round(lines[i].pos.y) << " "
				<< (int)round(lines[i].pos.x + lines[i].dir.x) << " "
				<< (int)round(lines[i].pos.y + lines[i].dir.y) << std::endl;
		}
		for (int i = 0; i < ncircle; i++)
		{
			output << (int)round(circles[i].center.x) << " " << (int)round(circles[i].center.y) << " "
				<< (int)round(circles[i].radius) << std::endl;
		}
	}
	else
	{
		for (int i = 0; i < nseg; i++)
		{
			output << segs[i].start.x << " " << segs[i].start.y << " "
				<< segs[i].end.x << " " << segs[i].end.y << std::endl;
		}
		for (int i = 0; i < nray; i++)
		{
			output << rays[i].start.x << " " << rays[i].start.y << " "
				<< rays[i].start.x + rays[i].dir.x << " "
				<< rays[i].start.y + rays[i].dir.y << std::endl;
		}
		for (int i = 0; i < nline; i++)
		{
			output << lines[i].pos.x << " " << lines[i].pos.y << " "
				<< lines[i].pos.x + lines[i].dir.x << " "
				<< lines[i].pos.y + lines[i].dir.y << std::endl;
		}
		for (int i = 0; i < ncircle; i++)
		{
			output << circles[i].center.x << " " << circles[i].center.y << " "
				<< circles[i].radius << std::endl;
		}
	}

	delete[] segs;
	delete[] rays;
	delete[] lines;
	delete[] circles;
	return 0;
}