void advancing_front (const Point_set& points, Scene_polyhedron_item* new_item, double size,
                        double radius_ratio_bound = 5., double beta = 0.52)
  {

    // TODO: build DT with indices
    
    Polyhedron& P = * const_cast<Polyhedron*>(new_item->polyhedron());
    Radius filter (size);

    typedef CGAL::Advancing_front_surface_reconstruction_vertex_base_3<Kernel> LVb;
    typedef CGAL::Advancing_front_surface_reconstruction_cell_base_3<Kernel> LCb;

    typedef CGAL::Triangulation_data_structure_3<LVb,LCb> Tds;
    typedef CGAL::Delaunay_triangulation_3<Kernel,Tds> Triangulation_3;

    typedef CGAL::Advancing_front_surface_reconstruction<Triangulation_3, Radius> Reconstruction;

    Triangulation_3 dt( boost::make_transform_iterator(points.begin_or_selection_begin(), Point_set_make_pair_point_index(points)),
                        boost::make_transform_iterator(points.end(), Point_set_make_pair_point_index(points)) );

    Reconstruction R(dt, filter);
    R.run(radius_ratio_bound, beta);
    CGAL::AFSR::construct_polyhedron(P, R);
						  
  }
 void operator()()
 {
   CGAL::jet_estimate_normals<Concurrency_tag>(points->all_or_selection_if_not_empty(),
                                               neighborhood_size,
                                               points->parameters().
                                               callback (*(this->callback())));
 }
  void advancing_front (const Point_set& points, Scene_polyhedron_item* new_item, double size)
  {
    Polyhedron& P = * const_cast<Polyhedron*>(new_item->polyhedron());
    Radius filter(10 * size);

    CGAL::advancing_front_surface_reconstruction (points.begin (), points.end (), P, filter);
						  
  }
 void operator()()
 {
   *result = CGAL::compute_average_spacing<Concurrency_tag>(
     points->all_or_selection_if_not_empty(),
     nb_neighbors,
     points->parameters().
     callback (*(this->callback())));
 }
Exemple #5
0
void print_point_set (const Point_set& point_set)
{
  std::cerr << "Content of point set:" << std::endl;
  for (Point_set::const_iterator it = point_set.begin();
       it != point_set.end(); ++ it)
    std::cerr << "* Point " << *it
              << ": " << point_set.point(*it) // or point_set[it]
              << " with normal " << point_set.normal(*it)
              << std::endl;
}
  void advancing_front (const Point_set& points, Scene_polyhedron_item* new_item, double size,
                        double radius_ratio_bound = 5., double beta = 0.52)
  {
    Polyhedron& P = * const_cast<Polyhedron*>(new_item->polyhedron());
    Radius filter (size);

    CGAL::advancing_front_surface_reconstruction (points.begin (), points.end (), P, filter,
                                                  radius_ratio_bound, beta);
						  
  }
  void compute_normals (Point_set& points, unsigned int neighbors)
  {
    CGAL::jet_estimate_normals<Concurrency_tag>(points.begin_or_selection_begin(), points.end(),
                                                points.point_map(),
                                                points.normal_map(),
                                                2 * neighbors);

    points.set_first_selected (CGAL::mst_orient_normals (points.begin(), points.end(),
                                                         points.point_map(),
                                                         points.normal_map(),
                                                         2 * neighbors));
    points.delete_selection();
  }
Geostat_grid* Pointset_geometry_xml_io::
  read_grid_geometry(QDir dir,const QDomElement& elem, std::string* errors) const {

	std::string grid_name = elem.attribute("name").toStdString();

	QDomElement elemGeom = elem.firstChildElement("Geometry");
	QString grid_size_str = elemGeom.attribute("size");

	bool ok_size;
	int size = grid_size_str.toInt(&ok_size);
	if(!ok_size) {
		errors->append("Failed to get the size of the grid");
		return 0;
	}


  SmartPtr<Named_interface> ni =
    Root::instance()->new_interface( "point_set://" + grid_name+"::"+grid_size_str.toStdString(),
                                     gridModels_manager + "/" + grid_name);
  Point_set* grid = dynamic_cast<Point_set*>( ni.raw_ptr() );
  if(grid==0) return 0;

  QFile file( dir.absolutePath()+"/coordinates.sgems" );
  if( !file.open( QIODevice::ReadOnly ) ) {
  	errors->append("Could not open file coordinates.sgems");
  	return grid;
  }

	QDataStream stream( &file );
#if QT_VERSION >= 0x040600
	stream.setFloatingPointPrecision(QDataStream::SinglePrecision);
#endif
 /*
  // read the coordinates of the points
  std::string coordsfile = dir.absolutePath().toStdString()+"/coordinates.sgems";
  std::fstream stream(coordsfile.c_str(),std::ios::in | std::ios::binary );
  if(stream.bad()) {
  	errors->append("Could not open file "+coordsfile);
  	return grid;
  }
*/
  std::vector<Point_set::location_type > coords;
  for( unsigned int k = 0; k < size; k ++ ) {
  	GsTLCoord x,y,z;
    stream >> x >> y >> z;
    coords.push_back( Point_set::location_type( x,y,z) );
  }
  grid->point_locations( coords );

  return grid;
}
 void operator()()
 {
   *result = CGAL::grid_simplify_point_set(*points,
                                           grid_size,
                                           points->parameters().
                                           callback (*(this->callback())));
 }
 void operator()()
 {
   *result = CGAL::hierarchy_simplify_point_set(*points,
                                                points->parameters().
                                                size(max_cluster_size).
                                                maximum_variation(max_surface_variation).
                                                callback (*(this->callback())));
 }
  void compute_normals (Point_set& points, unsigned int neighbors)
  {
    CGAL::jet_estimate_normals<Concurrency_tag>(points.begin(), points.end(),
                                                CGAL::make_normal_of_point_with_normal_pmap(Point_set::value_type()),
                                                2 * neighbors);
    
    points.erase (CGAL::mst_orient_normals (points.begin(), points.end(),
					    CGAL::make_normal_of_point_with_normal_pmap(Point_set::value_type()),
					    2 * neighbors),
		  points.end ());
  }
 void smooth_point_set (Point_set& points, unsigned int scale)
 {
   CGAL::jet_smooth_point_set<Concurrency_tag>(points.begin(), points.end(),
                                               scale);
 }
  void scale_space (const Point_set& points, ItemsInserter items,
		    unsigned int scale, bool generate_smooth = false,
                    bool separate_shells = false, bool force_manifold = true,
                    unsigned int samples = 300, unsigned int iterations = 4)
  {
    ScaleSpace reconstruct (scale, samples);
    reconstruct.reconstruct_surface(points.begin (), points.end (), iterations,
                                    separate_shells, force_manifold);

    for( unsigned int sh = 0; sh < reconstruct.number_of_shells(); ++sh )
      {
        Scene_polygon_soup_item* new_item
          = new Scene_polygon_soup_item ();
        new_item->setColor(Qt::magenta);
        new_item->setRenderingMode(FlatPlusEdges);
        new_item->init_polygon_soup(points.size(), reconstruct.number_of_triangles ());

        Scene_polygon_soup_item* smooth_item = NULL;
        if (generate_smooth)
          {
            smooth_item = new Scene_polygon_soup_item ();
            smooth_item->setColor(Qt::magenta);
            smooth_item->setRenderingMode(FlatPlusEdges);
            smooth_item->init_polygon_soup(points.size(), reconstruct.number_of_triangles ());
          }

        std::map<unsigned int, unsigned int> map_i2i;
        unsigned int current_index = 0;
    
        for (ScaleSpace::Triple_iterator it = reconstruct.shell_begin (sh);
             it != reconstruct.shell_end (sh); ++ it)
          {
            for (unsigned int ind = 0; ind < 3; ++ ind)
              {
                if (map_i2i.find ((*it)[ind]) == map_i2i.end ())
                  {
                    map_i2i.insert (std::make_pair ((*it)[ind], current_index ++));
                    Point p = points[(*it)[ind]].position();
                    new_item->new_vertex (p.x (), p.y (), p.z ());
                    
                    if (generate_smooth)
                      {
                        p = *(reconstruct.points_begin() + (*it)[ind]);
                        smooth_item->new_vertex (p.x (), p.y (), p.z ());
                      }
                  }
              }
            new_item->new_triangle( map_i2i[(*it)[0]],
                                    map_i2i[(*it)[1]],
                                    map_i2i[(*it)[2]] );
            if (generate_smooth)
              smooth_item->new_triangle( map_i2i[(*it)[0]],
                                         map_i2i[(*it)[1]],
                                         map_i2i[(*it)[2]] );
              
          }

        *(items ++) = new_item;
        if (generate_smooth)
          *(items ++) = smooth_item;
      }

    if (force_manifold)
      {
        std::ptrdiff_t num = std::distance( reconstruct.garbage_begin(  ),
                                            reconstruct.garbage_end(  ) );

        Scene_polygon_soup_item* new_item
          = new Scene_polygon_soup_item ();
        new_item->setColor(Qt::blue);
        new_item->setRenderingMode(FlatPlusEdges);
        new_item->init_polygon_soup(points.size(), num);

        Scene_polygon_soup_item* smooth_item = NULL;
        if (generate_smooth)
          {
            smooth_item = new Scene_polygon_soup_item ();
            smooth_item->setColor(Qt::blue);
            smooth_item->setRenderingMode(FlatPlusEdges);
            smooth_item->init_polygon_soup(points.size(), num);
          }

        std::map<unsigned int, unsigned int> map_i2i;

        unsigned int current_index = 0;
        for (ScaleSpace::Triple_iterator it=reconstruct.garbage_begin(),
               end=reconstruct.garbage_end();it!=end;++it)
          {
            for (unsigned int ind = 0; ind < 3; ++ ind)
              {
                if (map_i2i.find ((*it)[ind]) == map_i2i.end ())
                  {
                    map_i2i.insert (std::make_pair ((*it)[ind], current_index ++));
                    Point p = points[(*it)[ind]].position();
                    new_item->new_vertex (p.x (), p.y (), p.z ());
                    
                    if (generate_smooth)
                      {
                        p = *(reconstruct.points_begin() + (*it)[ind]);
                        smooth_item->new_vertex (p.x (), p.y (), p.z ());
                      }
                  }

              }
            new_item->new_triangle( map_i2i[(*it)[0]],
                                    map_i2i[(*it)[1]],
                                    map_i2i[(*it)[2]] );
            if (generate_smooth)
              smooth_item->new_triangle( map_i2i[(*it)[0]],
                                         map_i2i[(*it)[1]],
                                         map_i2i[(*it)[2]] );
          }

        *(items ++) = new_item;
        if (generate_smooth)
          *(items ++) = smooth_item;

      }
  }
  unsigned int scale_of_noise (const Point_set& points, double& size)
  {
    Tree tree(points.begin(), points.end());
    
    double ratio_kept = (points.size() < 1000)
      ? 1. : 1000. / (points.size());
    
    std::vector<Point> subset;
    for (std::size_t i = 0; i < points.size (); ++ i)
      if (rand() / (double)RAND_MAX < ratio_kept)
    	subset.push_back (points[i]);
    
    std::vector<unsigned int> scales;
    generate_scales (std::back_inserter (scales));

    std::vector<unsigned int> chosen;
    
    for (std::size_t i = 0; i < subset.size (); ++ i)
      {
    	Neighbor_search search(tree, subset[i],scales.back());
	double current = 0.;
    	unsigned int nb = 0;
    	std::size_t index = 0;
	double minimum = (std::numeric_limits<double>::max)();
	unsigned int c = 0;
	
    	for (Search_iterator search_iterator = search.begin();
    	     search_iterator != search.end (); ++ search_iterator, ++ nb)
    	  {
	    current += search_iterator->second;

    	    if (nb + 1 == scales[index])
    	      {
		double score = std::sqrt (current / scales[index])
		  / std::pow (scales[index], 0.375); // NB ^ (5/12)

		if (score < minimum)
		  {
		    minimum = score;
		    c = scales[index];
		  }

    		++ index;
    		if (index == scales.size ())
    		  break;
    	      }
    	  }
	chosen.push_back (c);
      }

    std::sort (chosen.begin (), chosen.end());

    unsigned int noise_scale = chosen[chosen.size() / 2];
    size = 0.;
    for (std::size_t i = 0; i < subset.size (); ++ i)
      {
    	Neighbor_search search(tree, subset[i], noise_scale);
	size += std::sqrt ((-- search.end())->second);
      }
    size /= subset.size();

    
    return noise_scale;
  }
  void simplify_point_set (Point_set& points, double size)
  {
    points.erase (CGAL::grid_simplify_point_set (points.begin (), points.end (), size),
		  points.end ());
  }
  unsigned int scale_of_anisotropy (const Point_set& points, double& size)
  {
    Tree tree(points.begin(), points.end());
    
    double ratio_kept = (points.size() < 1000)
      ? 1. : 1000. / (points.size());
    
    std::vector<Point> subset;
    for (std::size_t i = 0; i < points.size (); ++ i)
      if (rand() / (double)RAND_MAX < ratio_kept)
    	subset.push_back (points[i]);
    
    std::vector<unsigned int> scales;
    generate_scales (std::back_inserter (scales));

    std::vector<unsigned int> chosen;

    for (std::size_t i = 0; i < subset.size (); ++ i)
      {
    	Neighbor_search search(tree, subset[i],scales.back());
	double current = 0.;
    	unsigned int nb = 0;
    	std::size_t index = 0;
	double maximum = 0.;
	unsigned int c = 0;
	
    	for (Search_iterator search_iterator = search.begin();
    	     search_iterator != search.end (); ++ search_iterator, ++ nb)
    	  {
	    current += search_iterator->second;

    	    if (nb + 1 == scales[index])
    	      {
		double score = std::sqrt (current / scales[index])
		  / std::pow (scales[index], 0.75); // NB ^ (3/4)

		if (score > maximum)
		  {
		    maximum = score;
		    c = scales[index];
		  }

    		++ index;
    		if (index == scales.size ())
    		  break;
    	      }
    	  }
	chosen.push_back (c);
      }

    double mean = 0.;
    for (std::size_t i = 0; i < chosen.size(); ++ i)
      mean += chosen[i];
    mean /= chosen.size();
    unsigned int aniso_scale = static_cast<unsigned int>(mean);

    size = 0.;
    for (std::size_t i = 0; i < subset.size (); ++ i)
      {
    	Neighbor_search search(tree, subset[i], aniso_scale);
	size += std::sqrt ((-- search.end())->second);
      }
    size /= subset.size();
    
    return aniso_scale;
  }
bool poisson_reconstruct(FaceGraph* graph,
                         Point_set& points,
                         typename Traits::FT sm_angle, // Min triangle angle (degrees).
                         typename Traits::FT sm_radius, // Max triangle size w.r.t. point set average spacing.
                         typename Traits::FT sm_distance, // Approximation error w.r.t. point set average spacing.
                         const QString& solver_name, // solver name
                         bool use_two_passes,
                         bool do_not_fill_holes)
{
  // Poisson implicit function
  typedef CGAL::Poisson_reconstruction_function<Traits> Poisson_reconstruction_function;

  // Surface mesher
  typedef CGAL::Surface_mesh_default_triangulation_3 STr;
  typedef CGAL::Surface_mesh_complex_2_in_triangulation_3<STr> C2t3;
  typedef CGAL::Implicit_surface_3<Traits, Poisson_reconstruction_function> Surface_3;

  // AABB tree
  typedef CGAL::AABB_face_graph_triangle_primitive<FaceGraph> Primitive;
  typedef CGAL::AABB_traits<Traits, Primitive> AABB_traits;
  typedef CGAL::AABB_tree<AABB_traits> AABB_tree;
    CGAL::Timer task_timer; task_timer.start();

    //***************************************
    // Checks requirements
    //***************************************

    if (points.size() == 0)
    {
      std::cerr << "Error: empty point set" << std::endl;
     return false;
    }

    bool points_have_normals = points.has_normal_map();
    if ( ! points_have_normals )
    {
      std::cerr << "Input point set not supported: this reconstruction method requires oriented normals" << std::endl;
     return false;
    }

    CGAL::Timer reconstruction_timer; reconstruction_timer.start();

    //***************************************
    // Computes implicit function
    //***************************************

 
    std::cerr << "Computes Poisson implicit function "
              << "using " << solver_name.toLatin1().data() << " solver...\n";
              
    
    // Creates implicit function from the point set.
    // Note: this method requires an iterator over points
    // + property maps to access each point's position and normal.
    Poisson_reconstruction_function function(points.begin_or_selection_begin(), points.end(),
                                             points.point_map(), points.normal_map());

    bool ok = false;    
    #ifdef CGAL_EIGEN3_ENABLED
    if(solver_name=="Eigen - built-in simplicial LDLt")
    {
      CGAL::Eigen_solver_traits<Eigen::SimplicialCholesky<CGAL::Eigen_sparse_matrix<double>::EigenType> > solver;
      ok = function.compute_implicit_function(solver, use_two_passes);
    }
    if(solver_name=="Eigen - built-in CG")
    {
      CGAL::Eigen_solver_traits<Eigen::ConjugateGradient<CGAL::Eigen_sparse_matrix<double>::EigenType> > solver;
      solver.solver().setTolerance(1e-6);
      solver.solver().setMaxIterations(1000);
      ok = function.compute_implicit_function(solver, use_two_passes);
    }
    #endif

    // Computes the Poisson indicator function f()
    // at each vertex of the triangulation.
    if ( ! ok )
    {
      std::cerr << "Error: cannot compute implicit function" << std::endl;
     return false;
    }

    // Prints status
    std::cerr << "Total implicit function (triangulation+refinement+solver): " << task_timer.time() << " seconds\n";
    task_timer.reset();

    //***************************************
    // Surface mesh generation
    //***************************************

    std::cerr << "Surface meshing...\n";

    // Computes average spacing
    Kernel::FT average_spacing = CGAL::compute_average_spacing<Concurrency_tag>(points.all_or_selection_if_not_empty(),
                                                                                6 /* knn = 1 ring */,
                                                                                points.parameters());

    // Gets one point inside the implicit surface
    Kernel::Point_3 inner_point = function.get_inner_point();
    Kernel::FT inner_point_value = function(inner_point);
    if(inner_point_value >= 0.0)
    {
      std::cerr << "Error: unable to seed (" << inner_point_value << " at inner_point)" << std::endl;
     return false;
    }

    // Gets implicit function's radius
    Kernel::Sphere_3 bsphere = function.bounding_sphere();
    Kernel::FT radius = std::sqrt(bsphere.squared_radius());

    // Defines the implicit surface: requires defining a
  	// conservative bounding sphere centered at inner point.
    Kernel::FT sm_sphere_radius = 5.0 * radius;
    Kernel::FT sm_dichotomy_error = sm_distance*average_spacing/1000.0; // Dichotomy error must be << sm_distance
    Surface_3 surface(function,
                      Kernel::Sphere_3(inner_point,sm_sphere_radius*sm_sphere_radius),
                      sm_dichotomy_error/sm_sphere_radius);

    // Defines surface mesh generation criteria
    CGAL::Surface_mesh_default_criteria_3<STr> criteria(sm_angle,  // Min triangle angle (degrees)
                                                        sm_radius*average_spacing,  // Max triangle size
                                                        sm_distance*average_spacing); // Approximation error

    CGAL_TRACE_STREAM << "  make_surface_mesh(sphere center=("<<inner_point << "),\n"
                      << "                    sphere radius="<<sm_sphere_radius<<",\n"
                      << "                    angle="<<sm_angle << " degrees,\n"
                      << "                    triangle size="<<sm_radius<<" * average spacing="<<sm_radius*average_spacing<<",\n"
                      << "                    distance="<<sm_distance<<" * average spacing="<<sm_distance*average_spacing<<",\n"
                      << "                    dichotomy error=distance/"<<sm_distance*average_spacing/sm_dichotomy_error<<",\n"
                      << "                    Manifold_with_boundary_tag)\n";

    // Generates surface mesh with manifold option
    STr tr; // 3D Delaunay triangulation for surface mesh generation
    C2t3 c2t3(tr); // 2D complex in 3D Delaunay triangulation
    CGAL::make_surface_mesh(c2t3,                                 // reconstructed mesh
                            surface,                              // implicit surface
                            criteria,                             // meshing criteria
                            CGAL::Manifold_with_boundary_tag());  // require manifold mesh

    // Prints status
    std::cerr << "Surface meshing: " << task_timer.time() << " seconds, "
                                     << tr.number_of_vertices() << " output vertices"
                                     << std::endl;
    task_timer.reset();

    if(tr.number_of_vertices() == 0)
     return false;

    // Converts to polyhedron
    CGAL::facets_in_complex_2_to_triangle_mesh(c2t3, *graph);

    // Prints total reconstruction duration
    std::cerr << "Total reconstruction (implicit function + meshing): " << reconstruction_timer.time() << " seconds\n";

    //***************************************
    // Computes reconstruction error
    //***************************************

    // Constructs AABB tree and computes internal KD-tree
    // data structure to accelerate distance queries
    AABB_tree tree(faces(*graph).first, faces(*graph).second, *graph);
    tree.accelerate_distance_queries();

    // Computes distance from each input point to reconstructed mesh
    double max_distance = DBL_MIN;
    double avg_distance = 0;

    std::set<typename boost::graph_traits<FaceGraph>::face_descriptor> faces_to_keep;
    
    for (Point_set::const_iterator p=points.begin_or_selection_begin(); p!=points.end(); p++)
    {
      typename AABB_traits::Point_and_primitive_id pap = tree.closest_point_and_primitive (points.point (*p));
      double distance = std::sqrt(CGAL::squared_distance (pap.first, points.point(*p)));
      
      max_distance = (std::max)(max_distance, distance);
      avg_distance += distance;

      typename boost::graph_traits<FaceGraph>::face_descriptor f = pap.second;
      faces_to_keep.insert (f);  
    }
    avg_distance /= double(points.size());

    std::cerr << "Reconstruction error:\n"
              << "  max = " << max_distance << " = " << max_distance/average_spacing << " * average spacing\n"
              << "  avg = " << avg_distance << " = " << avg_distance/average_spacing << " * average spacing\n";

    if (do_not_fill_holes)
      {
        typename boost::graph_traits<FaceGraph>::face_iterator it = faces(*graph).begin ();
        while (it != faces(*graph).end ())
	  {
            typename boost::graph_traits<FaceGraph>::face_iterator current = it ++;

            if (faces_to_keep.find (*current) == faces_to_keep.end ())
            {
              CGAL::Euler::remove_face(halfedge (*current, *graph), *graph);
            }

	  }

      }
    return true;
}
Exemple #18
0
Geostat_grid* Csv_poinset_infilter::read( std::ifstream& infile ) {

	QByteArray tmp = dialog_->name().simplified().toLatin1();
	std::string name( tmp.constData() );

  int X_col_id = dialog_->X_column_index();
  int Y_col_id = dialog_->Y_column_index();
  int Z_col_id = dialog_->Z_column_index();

  if( X_col_id == Y_col_id || X_col_id == Z_col_id || Y_col_id == Z_col_id ) {
    GsTLcerr << "The same column was selected for multiple coordinates \n" << gstlIO::end;
    return 0;
  }

  bool use_no_data_value = dialog_->use_no_data_value();
  float no_data_value = GsTLGridProperty::no_data_value;
  if( dialog_->use_no_data_value() ) {
    no_data_value = dialog_->no_data_value();
  }


  std::string str;
  std::getline(infile, str);
  QString qstr(str.c_str());
  QStringList property_names = qstr.split(",");

  bool is_x_provided = dialog_->X_column_name() != "None";
  bool is_y_provided = dialog_->Y_column_name() != "None";
  bool is_z_provided = dialog_->Z_column_name() != "None";
  if(is_x_provided) property_names.removeOne(dialog_->X_column_name());
  if(is_y_provided) property_names.removeOne(dialog_->Y_column_name());
  if(is_z_provided) property_names.removeOne(dialog_->Z_column_name());


  std::vector< std::vector< QString > > property_values( property_names.size() );
  std::vector< Point_set::location_type > point_locations;

//  For a csv file no data value is indicated by an empty field e.g. {34,,5.5}
  while( std::getline(infile, str) ) {
    qstr = str.c_str();
    QStringList fields = qstr.split(",");

    Point_set::location_type loc;
    if(is_x_provided) loc[0] = fields[X_col_id].toDouble();
    if(is_y_provided) loc[1] = fields[Y_col_id].toDouble();
    if(is_z_provided) loc[2] = fields[Z_col_id].toDouble();
    point_locations.push_back(loc);

    unsigned int i=0;
   for(unsigned int j=0;j<fields.size();j++) {
      if(j==0) i=0;
      if(j != X_col_id && j != Y_col_id && j != Z_col_id) {
        property_values[i].push_back(fields[j]);
        i++;
      }
    }
  }
  
//   done reading file
//----------------------------

  int point_set_size = point_locations.size();
  appli_message( "read " << point_set_size << " points" );

  // We now have a vector containing all the locations and another one with
  // all the property values.
  // Create a pointset, initialize it with the data we collected, and we're done
 
  // ask manager to get a new pointset and initialize it
  SmartPtr<Named_interface> ni =
    Root::instance()->interface( gridModels_manager + "/" + name );

  if( ni.raw_ptr() != 0 ) {
    GsTLcerr << "object " << name << " already exists\n" << gstlIO::end;
    return 0;
  }

  std::string size_str = String_Op::to_string( point_set_size );
  ni = Root::instance()->new_interface( "point_set://" + size_str, 
				  gridModels_manager + "/" + name );
  Point_set* pset = dynamic_cast<Point_set*>( ni.raw_ptr() );
  appli_assert( pset != 0 );

  pset->point_locations( point_locations );


  for( unsigned int k= 0; k < property_names.size(); k++ ) {
  // Need to find out if property is categorical
    unsigned int check_size = std::min(30,static_cast<int>(property_values[k].size()));
    bool is_categ = false;
    for(unsigned int i=0; i<check_size ; i++ ) {
      bool ok;
      property_values[k][i].toFloat(&ok);
      if(!ok)  {
        is_categ = true;
        break;
      }
    }

    if(!is_categ) {
      GsTLGridProperty* prop = pset->add_property( property_names[k].toStdString() );
      for( int l=0; l < point_set_size; l++ ) {
        float val = property_values[k][l].toFloat();
        if(use_no_data_value && val == no_data_value) 
          val = GsTLGridProperty::no_data_value;
        prop->set_value( val, l );
      }
    }
    else {
      //Create categorical definition
      // by default it is named: grid-propertyName
      std::string catdef_name = name+"-"+property_names[k].toStdString();
       ni = Root::instance()->new_interface( "categoricaldefinition://"+catdef_name,categoricalDefinition_manager +"/"+catdef_name );
        CategoricalPropertyDefinitionName* cat_def = 
            dynamic_cast<CategoricalPropertyDefinitionName*>(ni.raw_ptr());


      for( int i=0; i < point_set_size; i++ ) {
        cat_def->add_category(property_values[k][i].toStdString());
      }
      GsTLGridCategoricalProperty* prop = pset->add_categorical_property( property_names[k].toStdString(),cat_def->name() );
//      prop->set_category_definition(cat_def->name());
      QString no_data_value_str = QString().arg( no_data_value);
      for( int i=0; i < point_set_size; i++ ) {
        QString val =  property_values[k][i];
        if(use_no_data_value && val == no_data_value_str)  {
          prop->set_value( GsTLGridProperty::no_data_value, i );
        }
        else 
          prop->set_value( val.toStdString(), i );
      }
    }
  }


  return pset;
}
int main() {

  const int grid_size = 10;
  // Build grid with locally varying mean
  Cartesian_grid* lvm_grid = new Cartesian_grid( grid_size, grid_size, 1 );
  GsTLGridProperty* prop = lvm_grid->add_property( "trend", typeid( float ) );
  
  for( int i=0; i< grid_size*grid_size/2 ; i++ ) {
    prop->set_value( 0.0, i );
  }
  for( int i=grid_size*grid_size/2; i< grid_size*grid_size ; i++ ) {
    prop->set_value( 10.0, i );
  }
  Colocated_neighborhood* coloc_neigh = 
    dynamic_cast<Colocated_neighborhood*>( 
	  lvm_grid->colocated_neighborhood( "trend" )
       );


  // Build kriging grid 
  Cartesian_grid* krig_grid = new Cartesian_grid( grid_size, grid_size, 1 );
  GsTLGridProperty* krig_prop = 
    krig_grid->add_property( string("krig"), typeid( float )  );
  krig_grid->select_property( "krig");

  // Build harddata grid
  const int pointset_size = 4;
  Point_set* harddata = new Point_set( pointset_size );
  std::vector<GsTLPoint> locations;
  locations.push_back( GsTLPoint( 0,0,0 ) );
  locations.push_back( GsTLPoint( 1,5,0 ) );
  locations.push_back( GsTLPoint( 8,8,0 ) );
  locations.push_back( GsTLPoint( 5,2,0 ) );
  harddata->point_locations( locations );
  GsTLGridProperty* hard_prop = harddata->add_property( "poro" );
  
  for( int i=0; i<pointset_size; i++ ) {
    hard_prop->set_value( i, i );
  }

  harddata->select_property( "poro" );


  // Set up covariance
  Covariance<GsTLPoint> cov;
  cov.nugget(0.1);
  cov.add_structure( "Spherical" );
  cov.sill( 0, 0.9 );
  cov.set_geometry( 0, 10,10,10, 0,0,0 );

  Grid_initializer initializer;
  initializer.assign( krig_grid,
		      krig_prop,
		      harddata,
		      "poro" );
	
  for( int i=0; i< krig_prop->size(); i++ ) {
    if( krig_prop->is_harddata( i ) )
      cout << "value at " << i << ": " 
	   << krig_prop->get_value( i ) << endl;
  }

  krig_grid->select_property( "krig");

  Neighborhood* neighborhood = krig_grid->neighborhood( 20, 20, 1, 0,0,0,
							&cov, true );

  typedef GsTLPoint Location;
  typedef std::vector<double>::const_iterator weight_iterator;
  typedef SKConstraints_impl< Neighborhood, Location > SKConstraints;
  typedef SK_local_mean_combiner<weight_iterator, Neighborhood,
                                 Colocated_neighborhood> LVM_combiner;
  typedef Kriging_constraints< Neighborhood, Location > KrigingConstraints;
  typedef Kriging_combiner< weight_iterator, Neighborhood > KrigingCombiner;


  LVM_combiner combiner( *coloc_neigh );
  SKConstraints constraints;


  // initialize the algo
  Kriging algo;
  algo.simul_grid_ = krig_grid;
  algo.property_name_ = "krig";
  algo.harddata_grid_ = 0;
  algo.neighborhood_ = neighborhood;
  algo.covar_ = cov;
  algo.combiner_ = new KrigingCombiner( &combiner );
  algo.Kconstraints_ = new KrigingConstraints( &constraints );


  // Run and output the results
  algo.execute();

  ofstream ofile( "result.out" );
  if( !ofile ) {
    cerr << "can't create file result.out" << endl;
    return 1;
  }

  GsTLGridProperty* prop1 = krig_grid->select_property( "krig" );
  ofile << "kriging" << endl << "1" << endl << "krig" << endl ;
  for( int i=0; i< prop1->size(); i++ ) {
    if( prop1->is_informed( i ) )
      ofile << prop1->get_value( i ) << endl;
    else
      ofile << "-99" << endl;
  }
}
int main (int, char**)
{
  Point_set pts;

  pts.add_normal_map();
  
  bool map_added = false;
  Size_t_map echo_map;
  Color_map color_map;

  boost::tie (echo_map, map_added) = pts.add_property_map<std::size_t> ("echo");
  CGAL_assertion (map_added);
  boost::tie (color_map, map_added) = pts.add_property_map<Classification::RGB_Color> ("color");
  CGAL_assertion (map_added);

  for (std::size_t i = 0; i < 1000; ++ i)
  {
    Point_set::iterator it
      = pts.insert (Point (CGAL::get_default_random().get_double(),
                           CGAL::get_default_random().get_double(),
                           CGAL::get_default_random().get_double()),
                    Vector (CGAL::get_default_random().get_double(),
                            CGAL::get_default_random().get_double(),
                            CGAL::get_default_random().get_double()));
    echo_map[*it] = std::size_t(CGAL::get_default_random().get_int(0, 4));
    color_map[*it] = CGAL::make_array ((unsigned char)(CGAL::get_default_random().get_int(0, 255)),
                                       (unsigned char)(CGAL::get_default_random().get_int(0, 255)),
                                       (unsigned char)(CGAL::get_default_random().get_int(0, 255)));
  }

  Feature_set features;
  Feature_generator generator (features, pts, pts.point_map(),
                               5,  // using 5 scales
                               pts.normal_map(),
                               color_map, echo_map);

  CGAL_assertion (generator.number_of_scales() == 5);
  CGAL_assertion (features.size() == 80);

  Label_set labels;

  std::vector<int> training_set (pts.size(), -1);
  for (std::size_t i = 0; i < 20; ++ i)
  {
    std::ostringstream oss;
    oss << "label_" << i;
    Label_handle lh = labels.add(oss.str().c_str());

    for (std::size_t j = 0; j < 10; ++ j)
      training_set[std::size_t(CGAL::get_default_random().get_int(0, int(training_set.size())))] = int(i);
  }
  CGAL_assertion (labels.size() == 20);
  
  Classifier classifier (labels, features);
  
  classifier.train<CGAL::Sequential_tag> (training_set, 800);
#ifdef CGAL_LINKED_WITH_TBB
  classifier.train<CGAL::Parallel_tag> (training_set, 800);
#endif

  std::vector<int> label_indices(pts.size(), -1);
  
  Classification::classify<CGAL::Sequential_tag>
    (pts, labels, classifier, label_indices);

  Classification::classify_with_local_smoothing<CGAL::Sequential_tag>
    (pts, pts.point_map(), labels, classifier,
     generator.neighborhood().sphere_neighbor_query(0.01f),
     label_indices);

  Classification::classify_with_graphcut<CGAL::Sequential_tag>
    (pts, pts.point_map(), labels, classifier,
     generator.neighborhood().k_neighbor_query(12),
     0.2f, 10, label_indices);

#ifdef CGAL_LINKED_WITH_TBB
  Classification::classify<CGAL::Sequential_tag>
    (pts, labels, classifier, label_indices);

  Classification::classify_with_local_smoothing<CGAL::Sequential_tag>
    (pts, pts.point_map(), labels, classifier,
     generator.neighborhood().sphere_neighbor_query(0.01f),
     label_indices);

  Classification::classify_with_graphcut<CGAL::Sequential_tag>
    (pts, pts.point_map(), labels, classifier,
     generator.neighborhood().k_neighbor_query(12),
     0.2f, 10, label_indices);
#endif

  Classification::Evaluation evaluation (labels, training_set, label_indices);
  
  return EXIT_SUCCESS;
}
Geostat_grid*
Simulacre_input_filter::read_pointset( QDataStream& stream, 
                                      std::string* errors ) {
  
  char* name;
  stream >> name;
  std::string grid_name( name );

  Q_INT32 version;
  stream >> version;
  if( version < 100 ) {
    errors->append( "file too old" );
    return 0;
  }

  Q_UINT32 size;
  stream >> size;
  
  // create a new point set of the correct size
  std::ostringstream ostr;
  ostr << size;
  std::string final_grid_name;
  SmartPtr<Named_interface> ni = 
    Root::instance()->new_interface( "point_set://" + ostr.str(),
                                     gridModels_manager + "/" + grid_name,
                                     &final_grid_name );
  Point_set* grid = dynamic_cast<Point_set*>( ni.raw_ptr() );

  // get the property names
  Q_UINT32 properties_count;
  stream >> properties_count;

  std::vector< char* > prop_names( properties_count );
  for( unsigned int i = 0; i < properties_count; i++ ) 
    stream >> prop_names[i];
  
  // read the coordinates of the points
  std::vector<Point_set::location_type > coords;
  for( unsigned int k = 0; k < size; k ++ ) {
    float x,y,z;
    stream >> x >> y >> z;
    coords.push_back( Point_set::location_type( x,y,z) );
  }
  grid->point_locations( coords );


  // read all the properties
  for( unsigned int j = 0; j < properties_count; j++ ) {
    std::string prop_name( prop_names[j] );
    GsTLGridProperty* prop = grid->add_property( prop_name );
    for( GsTLInt k = 0; k < size ; k++ ) {
      float val;
      stream >> val;
      prop->set_value( val, k );
    }
  }

  for( unsigned int l = 0; l < properties_count; l++ ) {
    delete [] prop_names[l];
  }
  delete [] name;

  return grid;
}
 void simplify_point_set (Point_set& points, double size)
 {
   points.set_first_selected (CGAL::grid_simplify_point_set (points.begin (), points.end (), points.point_map(), size));
   points.delete_selection();
 }