Beispiel #1
0
void WCartesianChart::paintEvent(WPaintDevice *paintDevice)
{
  while (!areas().empty())
    delete areas().front();

  WPainter painter(paintDevice);
  painter.setRenderHint(WPainter::Antialiasing);
  paint(painter);
}
Beispiel #2
0
void ncc_tracker_t::move_search_corner( int corner, const Imath::V2f& d, bool symmetric)
{
	tracker_areas_t areas( get_value<tracker_areas_t>( *areas_));
	Imath::Box2f new_search_area = areas.search;
	new_search_area = drag_box_corner( new_search_area, corner, d, symmetric);
	areas.set_search_area( new_search_area);
	areas_->set_value( areas);
}
Beispiel #3
0
CollOfScalar EquelleRuntimeCPU::norm(const CollOfFace& faces) const
{
    const int n = faces.size();
    CollOfScalar::V areas(n);
    for (int i = 0; i < n; ++i) {
        areas[i] = grid_.face_areas[faces[i].index];
    }
    return areas;
}
Beispiel #4
0
Imath::Box2f ncc_tracker_t::search_area( float frame) const
{
	tracker_areas_t areas( get_value<tracker_areas_t>( *areas_));
	Imath::V2f p( track_pos( frame) + offset());
	Imath::Box2f box( p);
	box.min.x -= areas.search.min.x;
	box.min.y -= areas.search.min.y;
	box.max.x += areas.search.max.x;
	box.max.y += areas.search.max.y;
	return box;
}
Beispiel #5
0
Imath::Box2f ncc_tracker_t::reference_area() const
{
	tracker_areas_t areas( get_value<tracker_areas_t>( *areas_));
	Imath::V2f p( track_pos() + offset());

	Imath::Box2f box( p);
	box.min.x -= areas.reference.min.x;
	box.min.y -= areas.reference.min.y;
	box.max.x += areas.reference.max.x;
	box.max.y += areas.reference.max.y;
	return box;
}
Beispiel #6
0
Array<T> TriangleSoup::vertex_areas(RawArray<const TV3> X) const {
  GEODE_ASSERT(X.size()>=nodes());
  Array<T> areas(X.size());
  for (int t=0;t<elements.size();t++) {
    int i,j,k;elements[t].get(i,j,k);
    T area = T(1./6)*magnitude(cross(X[j]-X[i],X[k]-X[i]));
    areas[i] += area;
    areas[j] += area;
    areas[k] += area;
  }
  return areas;
}
Beispiel #7
0
void
test5()
{
    typedef std::piecewise_linear_distribution<> D;
    typedef std::mt19937_64 G;
    G g;
    double b[] = {10, 14};
    double p[] = {1, 1};
    const size_t Np = sizeof(p) / sizeof(p[0]) - 1;
    D d(b, b+Np+1, p);
    const int N = 1000000;
    std::vector<D::result_type> u;
    for (size_t i = 0; i < N; ++i)
    {
        D::result_type v = d(g);
        assert(d.min() <= v && v < d.max());
        u.push_back(v);
    }
    std::sort(u.begin(), u.end());
    int kp = -1;
    double a = std::numeric_limits<double>::quiet_NaN();
    double m = std::numeric_limits<double>::quiet_NaN();
    double bk = std::numeric_limits<double>::quiet_NaN();
    double c = std::numeric_limits<double>::quiet_NaN();
    std::vector<double> areas(Np);
    double S = 0;
    for (size_t i = 0; i < areas.size(); ++i)
    {
        assert(i < Np);
        areas[i] = (p[i]+p[i+1])*(b[i+1]-b[i])/2;
        S += areas[i];
    }
    for (size_t i = 0; i < areas.size(); ++i)
        areas[i] /= S;
    for (size_t i = 0; i < Np+1; ++i)
        p[i] /= S;
    for (size_t i = 0; i < N; ++i)
    {
        int k = std::lower_bound(b, b+Np+1, u[i]) - b - 1;
        if (k != kp)
        {
            a = 0;
            for (int j = 0; j < k; ++j)
                a += areas[j];
            assert(k < static_cast<int>(Np));
            m = (p[k+1] - p[k]) / (b[k+1] - b[k]);
            bk = b[k];
            c = (b[k+1]*p[k] - b[k]*p[k+1]) / (b[k+1] - b[k]);
            kp = k;
        }
        assert(std::abs(f(u[i], a, m, bk, c) - double(i)/N) < .001);
    }
}
Beispiel #8
0
Real3 MeshSurface::draw_position(boost::shared_ptr<RandomNumberGenerator>& rng) const
{
#ifdef HAVE_VTK
    vtkPolyData* polydata = reader_->GetOutput();
    std::vector<double> areas(polydata->GetNumberOfCells());
    for (vtkIdType i(0); i < polydata->GetNumberOfCells(); i++)
    {
        vtkCell* cell = polydata->GetCell(i);
        vtkTriangle* triangle = dynamic_cast<vtkTriangle*>(cell);
        double p0[3];
        double p1[3];
        double p2[3];
        triangle->GetPoints()->GetPoint(0, p0);
        triangle->GetPoints()->GetPoint(1, p1);
        triangle->GetPoints()->GetPoint(2, p2);
        const double area = vtkTriangle::TriangleArea(p0, p1, p2);
        // std::cout << "p0: " << p0[0] << " " << p0[1] << " " << p0[2] << std::endl;
        // std::cout << "p1: " << p1[0] << " " << p1[1] << " " << p1[2] << std::endl;
        // std::cout << "p2: " << p2[0] << " " << p2[1] << " " << p2[2] << std::endl;
        // std::cout << "area of triangle " << i << ": " << area << std::endl;
        areas[i] = area;
    }
    const double rnd = rng->uniform(0.0, std::accumulate(areas.begin(), areas.end(), 0.0));
    double totarea = 0.0;
    for (vtkIdType i(0); i < polydata->GetNumberOfCells(); i++)
    {
        totarea += areas[i];
        if (rnd < totarea)
        {
            vtkCell* cell = polydata->GetCell(i);
            vtkTriangle* triangle = dynamic_cast<vtkTriangle*>(cell);
            double p0[3];
            double p1[3];
            double p2[3];
            triangle->GetPoints()->GetPoint(0, p0);
            triangle->GetPoints()->GetPoint(1, p1);
            triangle->GetPoints()->GetPoint(2, p2);
            const Real3 P0(p0[0], p0[1], p0[2]);
            const Real3 P1(p1[0], p1[1], p1[2]);
            const Real3 P2(p2[0], p2[1], p2[2]);
            const Real p(rng->uniform(0.0, 1.0)), q(rng->uniform(0.0, 1.0 - p));
            return (((P1 - P0) * p + (P2 - P0) * q + P0) + shift_) * ratio_;
        }
    }
    throw IllegalState("Never reach here.");
#else
    throw NotImplemented("not implemented yet.");
#endif
}
Beispiel #9
0
 int maxArea(vector<int> &height) {
     // Start typing your C/C++ solution below
     // DO NOT write int main() function
     std::vector<int> areas(height.size() - 1);
     for (int i=0; i<height.size()-1; ++i) {
         areas[i] = -1;
         for (int j=i+1; j<height.size(); ++j) {
             int a = (j-i)*min(height[j], height[i]);
             if (areas[i] < a) areas[i] = a;
         }
     }
     int max_area = -1;
     for (int i=0; i<areas.size(); ++i) max_area = std::max(max_area, areas[i]);
     return max_area;
 }
status_t
DebugReportGenerator::_DumpAreas(BFile& _output)
{
	BObjectList<AreaInfo> areas(20, true);
	status_t result = fDebuggerInterface->GetAreaInfos(areas);
	if (result != B_OK)
		return result;

	areas.SortItems(&_CompareAreas);

	BString data("\nAreas:\n");
	WRITE_AND_CHECK(_output, data);
	data.SetToFormat("\tID\t\tBase\t\tEnd\t\t\tSize (KiB)\tProtection\tLocking\t\t\tName\n\t");
	WRITE_AND_CHECK(_output, data);
	data.Truncate(0L);
	data.Append('-', 80);
	data.Append("\n");
	WRITE_AND_CHECK(_output, data);
	AreaInfo* info;
	BString protectionBuffer;
	char lockingBuffer[32];
	for (int32 i = 0; (info = areas.ItemAt(i)) != NULL; i++) {
		try {
			data.SetToFormat("\t%" B_PRId32 "\t0x%08" B_PRIx64 "\t"
				"0x%08" B_PRIx64 "\t%10" B_PRId64 "\t%-11s\t%-14s\t%s\n",
				info->AreaID(), info->BaseAddress(), info->BaseAddress()
					+ info->Size(), info->Size() / 1024,
				UiUtils::AreaProtectionFlagsToString(info->Protection(),
					protectionBuffer).String(),
				UiUtils::AreaLockingFlagsToString(info->Lock(), lockingBuffer,
					sizeof(lockingBuffer)), info->Name().String());

			WRITE_AND_CHECK(_output, data);
		} catch (...) {
			return B_NO_MEMORY;
		}
	}

	data = "\nProtection Flags: r - read, w - write, x - execute, "
		"s - stack, o - overcommit, c - cloneable, S - shared, k - kernel\n";
	WRITE_AND_CHECK(_output, data);

	return B_OK;
}
void model_parameters::initialization(void)
{
	NAreaAge.initialize();
 	CatchAreaAge.initialize();
 	CatchNatAge.initialize();
	Nage(1,1) = So*Bo/(1+beta*Bo);
	for(int i=sage+1 ; i <= nage ; i++)
	{
		Nage(1,i) = Nage(1,i-1) * mfexp(-za(i-1));
	}
	VulB(1) = elem_prod(elem_prod(Nage(1),va),wa);
	SB(1) = elem_prod(Nage(1),fa)*wa/2;
	tBo = Nage(1)*wa;
	calcmaxpos(tBo);
	varPos = maxPos*cvPos;
	PosX(1) = minPos + (maxPos - minPos) * (0.5+0.5*sin(indmonth(1)*PI/6 - mo*PI/6)); 
	VBarea(1,sarea) = VulB(1)* (cnorm(areas(sarea)+0.5,PosX(1),varPos));
	for(int r=sarea+1 ; r <= narea-1 ; r++)
	{
		VBarea(1,r) = VulB(1)* (cnorm(areas(r)+0.5,PosX(1),varPos)-cnorm(areas(r)-0.5,PosX(1),varPos));
		NAreaAge(1)(r) = elem_prod(Nage(1)(sage,nage),(cnorm(areas(r)+0.5,PosX(1),varPos)-cnorm(areas(r)-0.5,PosX(1),varPos)));
	}
	//VBarea(1,narea) = VulB(1)* (1.0-cnorm(areas(narea)-0.5,PosX(1),varPos));
	NationVulB(1,1) = sum(VBarea(1)(sarea,sarea+nationareas(1)-1)); 
	NationVulB(1,2) = sum(VBarea(1)(sarea+nationareas(1),narea)); 
	dvar_vector tmp1(sarea,narea);
	dvar_vector tmp2(sarea,narea);
	dvar_vector tmp3(sarea,narea);
	for(int rr= sarea; rr<=narea; rr++)
	{
		tmp1(rr)= VBarea(1)(rr)/ (NationVulB(1)(indnatarea(rr)) + 0.0001);
		tmp2(rr) = tmp1(rr)*TotEffyear(indnatarea(rr))(indyr(1));
		Effarea(1)(rr) = tmp2(rr)*TotEffmonth(indnatarea(rr))(indmonth(1));
	}
	for(int a= sage; a<= nage;a++)
	{
		dvar_vector propVBarea(sarea,narea);
		for(int rr =sarea; rr<=narea; rr++)
		{
			propVBarea(rr) = (cnorm(areas(rr)+0.5,PosX(1),varPos)-cnorm(areas(rr)-0.5,PosX(1),varPos))(a-sage+1);
			CatchAreaAge(1)(rr)(a) = q*Effarea(1)(rr)*va(a)/(q*Effarea(1)(rr)*va(a)+m)*(1-mfexp(-(q*Effarea(1)(rr)*va(a)+m)))*NAreaAge(1)(rr)(a);
			CatchNatAge(1)(indnatarea(rr))(a) += CatchAreaAge(1)(rr)(a);
			EffNatAge(indnatarea(rr))(1)(sage-2) = 1;
			EffNatAge(indnatarea(rr))(1)(sage-1) = indnatarea(rr);
			EffNatAge(indnatarea(rr))(1)(a) += Effarea(1)(rr)*propVBarea(rr);
		}
		//cout<<"propVBarea "<<propVBarea<<endl;
		//cout<<"Effarea(1) "<<Effarea(1)<<endl;
		Effage(1)(a) = Effarea(1)* propVBarea;
	}
}
Beispiel #12
0
/*!
 * \breif nms Non-maximum suppression
 * the algorithm is from https://github.com/ShaoqingRen/SPP_net/blob/master/nms%2Fnms_mex.cpp
 *
 * \param rects     area of faces
 * \param scores    score of faces
 * \param overlap   overlap threshold
 * \return          picked index
 */
static vector<int> nms(const vector<Rect>& rects, const vector<double>& scores, \
                       double overlap) {
  const int n = rects.size();
  vector<double> areas(n);

  typedef std::multimap<double, int> ScoreMapper;
  ScoreMapper map;
  for (int i = 0; i < n; i++) {
    map.insert(ScoreMapper::value_type(scores[i], i));
    areas[i] = rects[i].width*rects[i].height;
  }

  int picked_n = 0;
  vector<int> picked(n);
  while (map.size() != 0) {
    int last = map.rbegin()->second; // get the index of maximum score value
    picked[picked_n] = last;
    picked_n++;

    for (ScoreMapper::iterator it = map.begin(); it != map.end();) {
      int idx = it->second;
      double x1 = std::max(rects[idx].x, rects[last].x);
      double y1 = std::max(rects[idx].y, rects[last].y);
      double x2 = std::min(rects[idx].x + rects[idx].width, rects[last].x + rects[last].width);
      double y2 = std::min(rects[idx].y + rects[idx].height, rects[last].y + rects[last].height);
      double w = std::max(0., x2 - x1);
      double h = std::max(0., y2 - y1);
      double ov = w*h / (areas[idx] + areas[last] - w*h);
      if (ov > overlap) {
        ScoreMapper::iterator tmp = it;
        tmp++;
        map.erase(it);
        it = tmp;
      }
      else{
        it++;
      }
    }
  }

  picked.resize(picked_n);
  return picked;
}
Beispiel #13
0
static void nms_sorted_bboxes(const std::vector<BBoxRect>& bboxes, std::vector<int>& picked, float nms_threshold)
{
    picked.clear();

    const int n = bboxes.size();

    std::vector<float> areas(n);
    for (int i = 0; i < n; i++)
    {
        const BBoxRect& r = bboxes[i];

        float width = r.xmax - r.xmin;
        float height = r.ymax - r.ymin;

        areas[i] = width * height;
    }

    for (int i = 0; i < n; i++)
    {
        const BBoxRect& a = bboxes[i];

        int keep = 1;
        for (int j = 0; j < (int)picked.size(); j++)
        {
            const BBoxRect& b = bboxes[picked[j]];

            // intersection over union
            float inter_area = intersection_area(a, b);
            float union_area = areas[i] + areas[picked[j]] - inter_area;
//             float IoU = inter_area / union_area
            if (inter_area / union_area > nms_threshold)
                keep = 0;
        }

        if (keep)
            picked.push_back(i);
    }
}
Mat removeSmallBlobs(Mat bwImage) {
    vector<vector<Point> > contours, onlyContours(1);
    vector<Vec4i> hierarchy;
    
    findContours( bwImage.clone(), contours, hierarchy,
                 CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE );
    vector<double> areas(contours.size());
    if (contours.size() >0 ){
        for(size_t i= 0 ; i < contours.size() ; i ++) {
            areas[i] = contourArea(contours[i]);
            //        cout<<areas[i]<<",";
        }
        
        long biggestIndex = distance(areas.begin(), max_element(areas.begin(),areas.end()));
        //    cout<<biggestIndex<<":"<<areas[biggestIndex]<<endl;
        onlyContours[0] =contours[biggestIndex];
        Mat mask(bwImage.size(),CV_8UC1,Scalar::all(0));
        
        drawContours(mask, onlyContours, -1, Scalar(255), CV_FILLED);
        return mask;
    }
    return bwImage;
}
Point2f findMassCenter_BinaryBiggestBlob(const Mat& bw_img) {
    Mat full_bw_img = removeSmallBlobs(bw_img);
    threshold(bw_img, bw_img, 254, 255, CV_THRESH_BINARY);
    
    vector<vector<Point> > contours,onlyContours(1);
    
    vector<Vec4i> hierarchy;
    
    findContours( bw_img.clone(), contours, hierarchy,
                 CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE );
    
    if (contours.size() >0) {
        vector<int> areas(contours.size());
        for(size_t i= 0 ; i < contours.size() ; i ++) {
            areas[i] = contourArea(contours[i]);
            //        cout<<areas[i]<<",";
        }
        
        long biggestIndex = distance(areas.begin(), max_element(areas.begin(),areas.end()));
        //    cout<<biggestIndex<<":"<<areas[biggestIndex]<<endl;
        onlyContours[0] =contours[biggestIndex];
        
        /// Get the moments
        vector<Moments> mu(contours.size() );
        for( int i = 0; i < contours.size(); i++ )
        { mu[i] = moments( contours[i], false ); }
        
        ///  Get the mass centers:
        vector<Point2f> mc( contours.size() );
        for( int i = 0; i < contours.size(); i++ )
        { mc[i] = Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }
        
        return mc[0];
    } else
        return Point(0,0);
}
Beispiel #16
0
// TODO: Support to only set parcels within limited region.
void ParcelManager::
init(const Mesh &mesh) {
    Field<int> numParcelPerCell;
    numParcelPerCell.create("rp", "1", "parcel refinement", mesh, CENTER, mesh.domain().numDim());
    if (ConfigManager::hasKey("lasm", "parcel_refine_file_path")) {
        auto filePath = ConfigManager::getValue<string>("lasm", "parcel_refine_file_path");
        int ncId, ret, varId;
        int *buffer = new int[mesh.totalNumGrid(CENTER)];
        ret = nc_open(filePath.c_str(), NC_NOWRITE, &ncId);
        CHECK_NC_OPEN(ret, filePath);
        ret = nc_inq_varid(ncId, "rp", &varId);
        CHECK_NC_INQ_VARID(ret, filePath, "rp");
        ret = nc_get_var(ncId, varId, buffer);
        CHECK_NC_GET_VAR(ret, filePath, "rp");
        ret = nc_close(ncId);
        CHECK_NC_CLOSE(ret, filePath);
        for (uword i = 0; i < mesh.totalNumGrid(CENTER); ++i) {
            numParcelPerCell(i) = buffer[i];
        }
        delete [] buffer;
    } else {
        for (uword i = 0; i < mesh.totalNumGrid(CENTER); ++i) {
            numParcelPerCell(i) = 1;
        }
    }
    uvec n(mesh.domain().numDim());
    SpaceCoord x(mesh.domain().numDim());
    vec dx(mesh.domain().numDim());
    this->mesh = &mesh;
    TimeLevelIndex<2> timeIdx;
    int id = 0;
#ifdef LASM_USE_RLL_MESH
    vec areas(mesh.numGrid(1, FULL));
    vec areaWeights(mesh.numGrid(1, FULL));
    for (uword j = mesh.js(FULL); j <= mesh.je(FULL); ++j) {
        int cellIdx = mesh.wrapIndex(CENTER, mesh.is(FULL), j, mesh.ks(FULL));
        areas[j] = mesh.cellVolume(cellIdx);
        areaWeights[j] = exp(-0.1*fabs(mesh.sinLat(FULL, j)));
    }
    double maxArea = areas.max();
    vec size(mesh.domain().numDim());
    for (uword k = mesh.ks(FULL); k <= mesh.ke(FULL); ++k) {
        if (mesh.domain().numDim() == 3) {
            size[2] = mesh.gridInterval(2, HALF, k);
        }
        for (uword j = mesh.js(FULL)+1; j < mesh.je(FULL); ++j) {
            size[1] = mesh.gridInterval(1, HALF, j)*mesh.domain().radius();
            int numReducedLon = mesh.numGrid(0, FULL)/
                std::max(1, static_cast<int>(maxArea*areaWeights[j]/areas[j]));
            double dlon = PI2/numReducedLon;
            for (uword i = 0; i < numReducedLon; ++i) {
                double lon = i*dlon;
                if (mesh.domain().numDim() == 2) {
                    x.set(lon, mesh.lat(FULL, j));
                } else if (mesh.domain().numDim() == 3) {
                    x.set(lon, mesh.lat(FULL, j), mesh.lev(FULL, k));
                }
                x.transformToCart(mesh.domain());
                size[0] = dlon*mesh.domain().radius()*mesh.cosLat(FULL, j);
                Parcel *parcel = new Parcel;
                parcel->init(id++, 0);
                parcel->x(timeIdx) = x;
                parcel->meshIndex(timeIdx).locate(mesh, x);
                parcel->skeletonPoints().init(mesh, size);
                parcel->updateDeformMatrix(timeIdx);
                parcel->tracers().init();
                _parcels.push_back(parcel);
            }
        }
    }
#else
    for (uword i = 0; i < mesh.totalNumGrid(CENTER); ++i) {
        n.fill(pow(numParcelPerCell(i), 1.0/mesh.domain().numDim()));
        const SpaceCoord &x0 = mesh.gridCoord(CENTER, i);
        dx = mesh.cellSize(CENTER, i)/n;
        for (uword j = 0; j < numParcelPerCell(i); ++j) {
            subdivide(n, dx, j, x0, x);
            Parcel *parcel = new Parcel;
            parcel->init(id++, 0);
            parcel->x(timeIdx) = x;
            parcel->meshIndex(timeIdx).locate(mesh, x);
            parcel->skeletonPoints().init(mesh, dx);
            parcel->volume(timeIdx) = mesh.cellVolume(i)/numParcelPerCell(i);
            parcel->updateDeformMatrix(timeIdx);
            parcel->resetSkeletonPoints(timeIdx, mesh);
            parcel->tracers().init();
            _parcels.push_back(parcel);
        }
    }
#endif
} // init
Beispiel #17
0
int main() {

//  CGAL::Timer time;
//
//  time.start();
  
  cout << "Creating point cloud" << endl;

  simu.read();

  create();
  
  if(simu.create_points()) {

    //    set_alpha_circle( Tp , 2);
    //    set_alpha_under_cos(  Tp ) ;


    
    cout << "Creating velocity field " << endl;

    set_fields_TG( Tm ) ;
    //set_fields_cos( Tm ) ;
        
    cout << "Numbering particles " << endl;

    number(Tp);
    number(Tm);
  }

  int Nb=sqrt( simu.no_of_particles() + 1e-12);

  // Set up fft, and calculate initial velocities:
  
  move_info( Tm );
  move_info( Tp );

  CH_FFT fft( LL , Nb );

  load_fields_on_fft( Tm , fft );

  FT dt=simu.dt();
  FT mu=simu.mu();
  
  fft.all_fields_NS( dt * mu );

  fft.draw( "phi", 0, fft.field_f() );

  fft.draw( "press", 0, fft.field_p() );

  fft.draw( "vel_x", 0, fft.field_vel_x() );

  fft.draw( "vel_y", 0, fft.field_vel_y() );
  
  load_fields_from_fft( fft, Tm );
  
  // every step
  areas(Tp);
  quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );

  // just once!
  linear algebra(Tm);

  areas(Tm);
  quad_coeffs(Tm , simu.FEMm() ); volumes(Tm, simu.FEMm() );

  cout << "Setting up diff ops " << endl;

  // TODO: Are these two needed at all?
  //  if(simu.create_points()) {
  //  nabla(Tm);
  // TODO, they is, too clear why
  Delta(Tm);
    //  }

  const std::string mesh_file("mesh.dat");
  const std::string particle_file("particles.dat");

  // // step 0 draw.-
  //   draw(Tm, mesh_file     , true);
  //   draw(Tp, particle_file , true);
  
  cout << "Assigning velocities to particles " << endl;

#if defined FULL_FULL
  {
    Delta(Tp);
    linear algebra_p(Tp);
    from_mesh_full_v( Tm , Tp ,  algebra_p , kind::U);
  }
#elif defined FULL_LUMPED
  from_mesh_lumped_v( Tm , Tp , kind::U);
 #elif defined FLIP
  from_mesh_v(Tm , Tp , kind::U);
 #else
  from_mesh_v(Tm , Tp , kind::U);
#endif

// #if defined FULL_FULL
//   {
//     Delta(Tp);
//     linear algebra_p(Tp);
//     from_mesh_full( Tm , Tp ,  algebra_p,kind::ALPHA);
//   }
// #elif defined FULL_LUMPED
//   from_mesh_lumped( Tm , Tp , kind::ALPHA);
//  #elif defined FLIP
//   from_mesh(Tm , Tp , kind::ALPHA);
//  #else
//   from_mesh(Tm , Tp , kind::ALPHA);
// #endif

  cout << "Moving info" << endl;
  move_info( Tm );
  move_info( Tp );

  draw(Tm, mesh_file     , true);
  draw(Tp, particle_file , true);

  // return 1;
  
  simu.advance_time();
  simu.next_step();

  //  bool first_iter=true;

  CGAL::Timer time;

  time.start();

  std::ofstream log_file;

  log_file.open("main.log");

  bool is_overdamped = ( simu.mu() > 1 ) ; // high or low Re

  for(;
      simu.current_step() <= simu.Nsteps();
      simu.next_step()) {

    cout
      << "Step " << simu.current_step() 
      << " . Time " <<  simu.time()
      << " ; t step " << simu.dt()
      << endl;

    FT dt=simu.dt();

    FT dt2 = dt / 2.0 ;

    int iter=0;
    FT displ=1e10;

    FT min_displ=1e10;
    int min_iter=0;

    const int max_iter=8; //10;
    const FT  max_displ=  1e-8; // < 0 : disable

//  leapfrog, special first step.-
//    if(simu.current_step() == 1) dt2 *= 0.5;

//    dt2 *= 0.5;

    move_info(Tm);
    move_info(Tp);
    
    // iter loop
    for( ; ; iter++) {
      
      // comment for no move.-
      cout << "Moving half step " << endl;
      FT d0;

      displ = move( Tp , dt2 , d0 );

      areas(Tp);
      quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );
       
      cout
	<< "Iter " << iter
	<< " , moved avg " << d0 << " to half point, "
	<< displ << " from previous"
	<< endl;

      if( displ < min_displ) {
	min_displ=displ;
	min_iter=iter;
      }

      if( (displ < max_displ) && (iter !=0) )  {
	cout << "Convergence in  " << iter << " iterations " << endl;
	break;
      }

      if(  iter == max_iter-1 )  {
	cout << "Exceeded  " << iter-1 << " iterations " << endl;
	break;
      }

      cout << "Proj advected U0 velocities onto mesh " << endl;

#if defined FULL
      onto_mesh_full_v(Tp,Tm,algebra,kind::UOLD);
#elif defined FLIP
      flip_volumes   (Tp , Tm , simu.FEMm() );
      onto_mesh_flip_v(Tp,Tm,simu.FEMm(),kind::UOLD);
#else
      onto_mesh_delta_v(Tp,Tm,kind::UOLD);
#endif

      load_fields_on_fft( Tm , fft );

      FT b = mu * dt2;
     
      fft.all_fields_NS( b );
  
//      fft.evolve( b );
      
      load_fields_from_fft( fft , Tm );

// Search "FLIPincr" in CH_FFT.cpp to change accordingly!
// EITHER:
// FLIP idea: project only increments
      
       cout << "Proj Delta U from mesh onto particles" << endl;
      
 #if defined FULL_FULL
       {
 	Delta(Tp);
 	linear algebra_p(Tp);
 	from_mesh_full_v(Tm, Tp, algebra_p , kind::DELTAU);
       }
 #elif defined FULL_LUMPED
       from_mesh_lumped_v(Tm, Tp, kind::DELTAU);
 #elif defined FLIP
       from_mesh_v(Tm, Tp, kind::DELTAU);
 #else
       from_mesh_v(Tm, Tp, kind::DELTAU);
 #endif

       incr_v( Tp ,  kind::UOLD , kind::DELTAU , kind::U );


// OR:
// project the whole velocity
      
//      cout << "Proj U from mesh onto particles" << endl;
//      
//#if defined FULL_FULL
//      {
//	Delta(Tp);
//	linear algebra_p(Tp);
//	from_mesh_full_v(Tm, Tp, algebra_p , kind::U);
//      }
//#elif defined FULL_LUMPED
//      from_mesh_lumped_v(Tm, Tp, kind::U);
//#elif defined FLIP
//      from_mesh_v(Tm, Tp, kind::U);
//#else
//      from_mesh_v(Tm, Tp, kind::U);
//#endif

      

      
      // // substract spurious overall movement.-      

      //      zero_mean_v( Tm , kind::FORCE);

    } // iter loop


    cout << "Moving whole step: relative ";

    FT d0;
    
    displ=move( Tp , dt , d0 );

    cout
      <<  displ << " from half point, "
      <<  d0    << " from previous point"
      << endl;
    
      // comment for no move.-

    update_half_velocity( Tp , is_overdamped ); 

    update_half_alpha( Tp );

    areas(Tp);

    quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );

    // this, for the looks basically .-
    
    cout << "Proj U_t+1 , alpha_t+1 onto mesh " << endl;

#if defined FULL
    onto_mesh_full_v(Tp,Tm,algebra,kind::U);
    onto_mesh_full  (Tp,Tm,algebra,kind::ALPHA);
#elif defined FLIP
    flip_volumes(Tp , Tm , simu.FEMm() );
    onto_mesh_flip_v(Tp,Tm,simu.FEMm(),kind::U);
    onto_mesh_flip  (Tp,Tm,simu.FEMm(),kind::ALPHA);
#else
    onto_mesh_delta_v(Tp,Tm,kind::U);
    onto_mesh_delta  (Tp,Tm,kind::ALPHA);
#endif

    move_info( Tm );
    move_info( Tp );

    if(simu.current_step()%simu.every()==0) {
      draw(Tm, mesh_file     , true);
      draw(Tp, particle_file , true);
      fft.histogram( "phi", simu.current_step() , fft.field_fq() );
    }

    log_file
      << simu.current_step() << "  "
      << simu.time() << "  " ;

    // integrals( Tp , log_file);     log_file << "  ";
    // fidelity(  Tp , log_file );    log_file << endl;

    simu.advance_time();

  } // time loop

  time.stop();

  log_file.close();
  
  cout << "Total runtime: " << time.time() << endl;
  return 0;

}
Beispiel #18
0
nsRect nsRegion::GetLargestRectangle (const nsRect& aContainingRect) const {
  nsRect bestRect;

  if (GetNumRects() <= 1) {
    bestRect = GetBounds();
    return bestRect;
  }

  AxisPartition xaxis, yaxis;

  // Step 1: Calculate the grid lines
  nsRegionRectIterator iter(*this);
  const nsRect *currentRect;
  while ((currentRect = iter.Next())) {
    xaxis.InsertCoord(currentRect->x);
    xaxis.InsertCoord(currentRect->XMost());
    yaxis.InsertCoord(currentRect->y);
    yaxis.InsertCoord(currentRect->YMost());
  }
  if (!aContainingRect.IsEmpty()) {
    xaxis.InsertCoord(aContainingRect.x);
    xaxis.InsertCoord(aContainingRect.XMost());
    yaxis.InsertCoord(aContainingRect.y);
    yaxis.InsertCoord(aContainingRect.YMost());
  }

  // Step 2: Fill out the grid with the areas
  // Note: due to the ordering of rectangles in the region, it is not always
  // possible to combine steps 2 and 3 so we don't try to be clever.
  int32_t matrixHeight = yaxis.GetNumStops() - 1;
  int32_t matrixWidth = xaxis.GetNumStops() - 1;
  int32_t matrixSize = matrixHeight * matrixWidth;
  nsTArray<SizePair> areas(matrixSize);
  areas.SetLength(matrixSize);

  iter.Reset();
  while ((currentRect = iter.Next())) {
    int32_t xstart = xaxis.IndexOf(currentRect->x);
    int32_t xend = xaxis.IndexOf(currentRect->XMost());
    int32_t y = yaxis.IndexOf(currentRect->y);
    int32_t yend = yaxis.IndexOf(currentRect->YMost());

    for (; y < yend; y++) {
      nscoord height = yaxis.StopSize(y);
      for (int32_t x = xstart; x < xend; x++) {
        nscoord width = xaxis.StopSize(x);
        int64_t size = width*int64_t(height);
        if (currentRect->Intersects(aContainingRect)) {
          areas[y*matrixWidth+x].mSizeContainingRect = size;
        }
        areas[y*matrixWidth+x].mSize = size;
      }
    }
  }

  // Step 3: Find the maximum submatrix sum that does not contain a rectangle
  {
    // First get the prefix sum array
    int32_t m = matrixHeight + 1;
    int32_t n = matrixWidth + 1;
    nsTArray<SizePair> pareas(m*n);
    pareas.SetLength(m*n);
    for (int32_t y = 1; y < m; y++) {
      for (int32_t x = 1; x < n; x++) {
        SizePair area = areas[(y-1)*matrixWidth+x-1];
        if (!area.mSize) {
          area = SizePair::VeryLargeNegative();
        }
        area = area + pareas[    y*n+x-1]
                    + pareas[(y-1)*n+x  ]
                    - pareas[(y-1)*n+x-1];
        pareas[y*n+x] = area;
      }
    }

    // No longer need the grid
    areas.SetLength(0);

    SizePair bestArea;
    struct {
      int32_t left, top, right, bottom;
    } bestRectIndices = { 0, 0, 0, 0 };
    for (int32_t m1 = 0; m1 < m; m1++) {
      for (int32_t m2 = m1+1; m2 < m; m2++) {
        nsTArray<SizePair> B;
        B.SetLength(n);
        for (int32_t i = 0; i < n; i++) {
          B[i] = pareas[m2*n+i] - pareas[m1*n+i];
        }
        int32_t minIdx, maxIdx;
        SizePair area = MaxSum1D(B, n, &minIdx, &maxIdx);
        if (area > bestArea) {
          bestRectIndices.left = minIdx;
          bestRectIndices.top = m1;
          bestRectIndices.right = maxIdx;
          bestRectIndices.bottom = m2;
          bestArea = area;
        }
      }
    }

    bestRect.MoveTo(xaxis.StopAt(bestRectIndices.left),
                    yaxis.StopAt(bestRectIndices.top));
    bestRect.SizeTo(xaxis.StopAt(bestRectIndices.right) - bestRect.x,
                    yaxis.StopAt(bestRectIndices.bottom) - bestRect.y);
  }

  return bestRect;
}
Beispiel #19
0
    void cxy_CAD_helper::shapeToPointCloud(shapes::Mesh &shape
                                           , sensor_msgs::PointCloud &cloud
                                           , pcl::PointCloud<pcl::PointXYZ> &normals
                                           , const SamplingParams &params)
    {
        cloud.header.frame_id = shape.STRING_NAME;
        //srand(time(NULL));
        srand(1);

        if (params.sample_type == SampleType::RANDOM)
        {
            double max_area = 0;
            double running_tot = 0;
            std::vector<double> areas(shape.triangle_count);

            for (int i = 0; i < shape.triangle_count; i++)
            {
                float density = 100;
                double area;

                geometry_msgs::Point    v1;
                geometry_msgs::Point    v2;
                geometry_msgs::Point    v3;

                v1.x = shape.vertices[3*shape.triangles[3*i]];
                v1.y = shape.vertices[3*shape.triangles[3*i] + 1];
                v1.z = shape.vertices[3*shape.triangles[3*i] + 2];

                v2.x = shape.vertices[3*shape.triangles[3*i + 1]];
                v2.y = shape.vertices[3*shape.triangles[3*i + 1] + 1];
                v2.z = shape.vertices[3*shape.triangles[3*i + 1] + 2];

                v3.x = shape.vertices[3*shape.triangles[3*i + 2]];
                v3.y = shape.vertices[3*shape.triangles[3*i + 2] + 1];
                v3.z = shape.vertices[3*shape.triangles[3*i + 2] + 2];

                area = this->findArea(v1, v2, v3, density);

                running_tot = running_tot + area;
                areas[i] = running_tot;
                if (area > max_area)
                    max_area = area;
            }

            std::for_each(areas.begin(), areas.end(),
                    [&](double& elm)
                    {
                        elm = elm / running_tot;
                        elm *= RAND_MAX;
                    }
            );
            for (int i = 0; i < params.number_of_points; i++)
            {
                int prob = rand() % RAND_MAX;
                int imax = areas.size();
                int imin = 0;
                int index = 0;
                int imid;

                while (imax >= imin)
                {
                    imid = imin + (int) ((imax - imin) / 2);

                    if (areas[imid] <= prob)
                        if (areas[imid + 1] > prob)
                        {
                            index = imid;
                            break;
                        }
                        else
                            imin = imid + 1;
                    else if (areas[imid] > prob)
                        if (areas[imid - 1] <= prob)
                        {
                            index = imid;
                            break;
                        }
                        else
                            imax = imid - 1;
                }

                geometry_msgs::Point    v1;
                geometry_msgs::Point    v2;
                geometry_msgs::Point    v3;

                v1.x = shape.vertices[3*shape.triangles[3*index]];
                v1.y = shape.vertices[3*shape.triangles[3*index] + 1];
                v1.z = shape.vertices[3*shape.triangles[3*index] + 2];

                v2.x = shape.vertices[3*shape.triangles[3*index + 1]];
                v2.y = shape.vertices[3*shape.triangles[3*index + 1] + 1];
                v2.z = shape.vertices[3*shape.triangles[3*index + 1] + 2];

                v3.x = shape.vertices[3*shape.triangles[3*index + 2]];
                v3.y = shape.vertices[3*shape.triangles[3*index + 2] + 1];
                v3.z = shape.vertices[3*shape.triangles[3*index + 2] + 2];

                // Find normals
                geometry_msgs::Vector3  normal;
                this->getNormal(v1, v2, v3, normal);
                pcl::PointXYZ   normal_pt(normal.x, normal.y, normal.z);
                normals.points.push_back(normal_pt);

                // Sample point
                geometry_msgs::Point32  point = sampleRandomPoint(v1, v2, v3);
                cloud.points.push_back(point);
            }
        }
        else if (params.sample_type == SampleType::GRID)
        {
            for (int i = 0; i < (shape.triangle_count); i++)
            {
                geometry_msgs::Point    v1;
                geometry_msgs::Point    v2;
                geometry_msgs::Point    v3;

                v1.x = shape.vertices[3*shape.triangles[3*i]];
                v1.y = shape.vertices[3*shape.triangles[3*i] + 1];
                v1.z = shape.vertices[3*shape.triangles[3*i] + 2];

                v2.x = shape.vertices[3*shape.triangles[3*i + 1]];
                v2.y = shape.vertices[3*shape.triangles[3*i + 1] + 1];
                v2.z = shape.vertices[3*shape.triangles[3*i + 1] + 2];

                v3.x = shape.vertices[3*shape.triangles[3*i + 2]];
                v3.y = shape.vertices[3*shape.triangles[3*i + 2] + 1];
                v3.z = shape.vertices[3*shape.triangles[3*i + 2] + 2];

                // Find normals
                geometry_msgs::Vector3  normal;
                this->getNormal(v1, v2, v3, normal);
                pcl::PointXYZ   normal_pt(normal.x, normal.y, normal.z);
                normals.points.push_back(normal_pt);

                std::list<geometry_msgs::Point32>   samples;
                this->sampleGridPoints(v1, v2, v3, samples, params.step_size);
                while (!samples.empty())
                {
                    geometry_msgs::Point32  point = samples.front();
                    samples.pop_front();
                    cloud.points.push_back(point);
                }
            }
        }
    }
Beispiel #20
0
int main() {

//  CGAL::Timer time;
//
//  time.start();
  
  cout << "Creating point cloud" << endl;

  simu.read();

  create();
  
  if(simu.create_points()) {

    //    set_alpha_circle( Tp , 2);
    //    set_alpha_under_cos(  Tp ) ;

    cout << "Creating alpha field " << endl;
    
    set_alpha_random(  Tm ) ;
    //set_alpha_cos( Tm );
    
    cout << "Numbering particles " << endl;

    number(Tp);
    number(Tm);
  }

  int Nb=sqrt( simu.no_of_particles() + 1e-12);

  // Set up fft, and calculate initial velocities:
  
  move_info( Tm );

  CH_FFT fft( LL , Nb );

  load_alpha_on_fft( Tm , fft );

  fft.all_fields();

  fft.draw( "phi", 0, fft.field_f() );

  fft.draw( "mu", 0, fft.field_mu() );

  fft.draw( "grad_mu_x", 0, fft.field_grad_mu_x() );

  fft.draw( "grad_mu_y", 0, fft.field_grad_mu_y() );

  fft.draw( "force_x", 0, fft.field_force_x() );

  fft.draw( "force_y", 0, fft.field_force_y() );

  fft.draw( "vel_x", 0, fft.field_vel_x() );

  fft.draw( "vel_y", 0, fft.field_vel_y() );
  
  load_fields_from_fft( fft, Tm );
  
  // every step
  areas(Tp);
  quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );

  // just once!
  linear algebra(Tm);

  areas(Tm);
  quad_coeffs(Tm , simu.FEMm() ); volumes(Tm, simu.FEMm() );

  cout << "Setting up diff ops " << endl;

  // TODO: Are these two needed at all?
  //  if(simu.create_points()) {
  //  nabla(Tm);
  // TODO, they is, too clear why
  Delta(Tm);
    //  }

  const std::string mesh_file("mesh.dat");
  const std::string particle_file("particles.dat");

  // // step 0 draw.-
  //   draw(Tm, mesh_file     , true);
  //   draw(Tp, particle_file , true);
  
  cout << "Assigning alpha to particles " << endl;


#if defined FULL_FULL
  {
    Delta(Tp);
    linear algebra_p(Tp);
    from_mesh_full( Tm , Tp ,  algebra_p,kind::ALPHA);
  }
#elif defined FULL_LUMPED
  from_mesh_lumped( Tm , Tp , kind::ALPHA);
 #elif defined FLIP
  from_mesh(Tm , Tp , kind::ALPHA);
 #else
  from_mesh(Tm , Tp , kind::ALPHA);
#endif

// #if defined FULL_FULL
//   {
//     Delta(Tp);
//     linear algebra_p(Tp);
//     from_mesh_full( Tm , Tp ,  algebra_p,kind::ALPHA);
//   }
// #elif defined FULL_LUMPED
//   from_mesh_lumped( Tm , Tp , kind::ALPHA);
//  #elif defined FLIP
//   from_mesh(Tm , Tp , kind::ALPHA);
//  #else
//   from_mesh(Tm , Tp , kind::ALPHA);
// #endif

  cout << "Moving info" << endl;
  move_info( Tm );
  move_info( Tp );

  draw(Tm, mesh_file     , true);
  draw(Tp, particle_file , true);

  //  return 1;
  
  simu.advance_time();
  simu.next_step();

  //  bool first_iter=true;

  CGAL::Timer time;

  time.start();

  std::ofstream log_file;

  log_file.open("main.log");

  bool is_overdamped = ( simu.mu() > 1 ) ; // high or low Re

  for(;
      simu.current_step() <= simu.Nsteps();
      simu.next_step()) {

    cout
      << "Step " << simu.current_step() 
      << " . Time " <<  simu.time()
      << " ; t step " << simu.dt()
      << endl;

    FT dt=simu.dt();

    FT dt2 = dt / 2.0 ;

    int iter=0;
    FT displ=1e10;

    FT min_displ=1e10;
    int min_iter=0;

    const int max_iter=5; //10;
    const FT  max_displ=  1e-8; // < 0 : disable

//  leapfrog, special first step.-
//    if(simu.current_step() == 1) dt2 *= 0.5;

//    dt2 *= 0.5;

    move_info(Tm);
    move_info(Tp);

    // iter loop
    for( ; iter<max_iter ; iter++) {

      // comment for no move.-
      displ = move( Tp , dt2 );

      cout << "Iter " << iter << " , moved avg " << displ << " to half point" << endl;

      if( displ < min_displ) {
	min_displ=displ;
	min_iter=iter;
      }

      if( (displ < max_displ) && (iter !=0) ) break;

      areas(Tp);
      quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );
       
      cout << "Proj U0, alpha0 onto mesh " << endl;

#if defined FULL
      onto_mesh_full  (Tp,Tm,algebra,kind::ALPHA);
#elif defined FLIP
      flip_volumes(Tp , Tm , simu.FEMm() );
      onto_mesh_flip  (Tp,Tm,simu.FEMm(),kind::ALPHA);
#else
      onto_mesh_delta  (Tp,Tm,kind::ALPHA);
#endif

      load_alpha_on_fft( Tm , fft );

      fft.all_fields();
  
      FT b = Db*dt2;

      fft.evolve( b );
      
      load_fields_from_fft( fft, Tm );

      cout << "Proj U, alpha from mesh " << endl;
      
#if defined FULL_FULL
      {
	Delta(Tp);
	linear algebra_p(Tp);
	from_mesh_full_v(Tm, Tp, algebra_p , kind::U);
	from_mesh_full( Tm , Tp ,  algebra_p,kind::ALPHA);
      }
#elif defined FULL_LUMPED
      from_mesh_lumped( Tm , Tp , kind::ALPHA);
      from_mesh_lumped_v(Tm, Tp, kind::U);
#elif defined FLIP
      from_mesh(Tm , Tp , kind::ALPHA);
      from_mesh_v(Tm, Tp, kind::U);
#else
      from_mesh(Tm , Tp , kind::ALPHA);
      from_mesh_v(Tm, Tp, kind::U);
#endif

      
      // // substract spurious overall movement.-      

      //      zero_mean_v( Tm , kind::FORCE);

    } // iter loop

      // comment for no move.-

    displ=move( Tp , dt );

    update_half_velocity( Tp , false );

      // comment for no move.-
      //    update_half_velocity( Tp , is_overdamped ); 

    update_half_alpha( Tp );

    areas(Tp);

    quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );

    // this, for the looks basically .-
    
    cout << "Proj U_t+1 , alpha_t+1 onto mesh " << endl;

#if defined FULL
    onto_mesh_full_v(Tp,Tm,algebra,kind::U);
    onto_mesh_full  (Tp,Tm,algebra,kind::ALPHA);
#elif defined FLIP
    flip_volumes(Tp , Tm , simu.FEMm() );
    onto_mesh_flip_v(Tp,Tm,simu.FEMm(),kind::U);
    onto_mesh_flip  (Tp,Tm,simu.FEMm(),kind::ALPHA);
#else
    onto_mesh_delta_v(Tp,Tm,kind::U);
    onto_mesh_delta  (Tp,Tm,kind::ALPHA);
#endif

    if(simu.current_step()%simu.every()==0) {
      draw(Tm, mesh_file     , true);
      draw(Tp, particle_file , true);
      fft.histogram( "phi", simu.current_step() , fft.field_fq() );
    }

    log_file
      << simu.current_step() << "  "
      << simu.time() << "  " ;

    // integrals( Tp , log_file);     log_file << "  ";
    // fidelity(  Tp , log_file );    log_file << endl;

    simu.advance_time();

  } // time loop

  time.stop();

  log_file.close();
  
  cout << "Total runtime: " << time.time() << endl;
  return 0;

}
Beispiel #21
0
/*******************************************************************************
* Function:      subtractBGOpenDiagonal  
* Description:   BG subtraction via opening with diagonal structuring elements
* Arguments:
	inImg           -   input image
	bgsImg          -   BG subtracted image
	threshVal       -   threshold value for converting to binary image
	seLength        -   length of structuring elements
	
* Returns:       void
* Comments:
* Revision: 
*******************************************************************************/
int
FGExtraction::subtractBGOpenDiagonal(InputArray src, OutputArray dst, int threshVal, int seLength)
{
    // generate binary image by thresholding
	Mat bin;
	double thresh = threshold(src, bin, threshVal, 255, THRESH_BINARY);

	// opening by horizontal structuring element
	//Mat structElemHorizontal = Mat::ones(1, seLength, CV_8U);
	//morphologyEx(bin, dst, MORPH_OPEN, structElemHorizontal);

	// opening by vertical structuring element
	//Mat structElemVertical = Mat::ones(seLength, 1, CV_8U);
	//morphologyEx(dst, dst, MORPH_OPEN, structElemVertical);

	//imshow("src", src);
	//imshow("bin", bin);
	//waitKey(0);

    // opening by first diagonal structuring element
	Mat structElemBackSlash = Mat::eye(seLength, seLength, CV_8U);
	morphologyEx(bin, dst, MORPH_OPEN, structElemBackSlash);

	//imshow("dst1", dst);
	//waitKey(0);

    // opening by second diagonal structuring element
	Mat structElemSlash;
	flip(structElemBackSlash, structElemSlash, 0);
	morphologyEx(dst, dst, MORPH_OPEN, structElemSlash);

	//imshow("dst2", dst);
	//waitKey(0);

	// eliminate small noise
	Mat structElemEllip = getStructuringElement(MORPH_ELLIPSE, Size(seLength, seLength));
	morphologyEx(dst, dst, MORPH_OPEN, structElemEllip);

	//imshow("dst3", dst);
	//waitKey(0);


	// get object size
	Mat dstImg = dst.getMat();
	vector<vector<Point>> contours = extractContours(dstImg);
	if (contours.size()==0)
		return 1;

    Mat mask = Mat::zeros(_bgsImg.size(), CV_8U); 
	vector<int> areas(contours.size());
	int cnt = 0;
	int argMax = 0;
	int max_area = 0;
    for(vector<vector<Point> >::const_iterator it = contours.begin(); it != contours.end(); ++it){
        Rect uprightBox = boundingRect(*it);
		areas[cnt] = uprightBox.height*uprightBox.width;
		if (areas[cnt]>max_area) {
			max_area = areas[cnt];
			argMax = cnt;
		}
		cnt++;
	}
	vector<Point> largestContour = contours[argMax];	//***** only use the largest contour
	RotatedRect orientedBox = orientedBoundingBox(largestContour);

	int updateSeL = int(min(orientedBox.size.width, orientedBox.size.height)/5.0+0.5);

	// opening by first diagonal structuring element
	structElemBackSlash = Mat::eye(updateSeL, updateSeL, CV_8U);
	morphologyEx(bin, dst, MORPH_OPEN, structElemBackSlash);
	
	//imshow("dst1", dst);
	//waitKey(0);

    // opening by second diagonal structuring element
	flip(structElemBackSlash, structElemSlash, 0);
	morphologyEx(dst, dst, MORPH_OPEN, structElemSlash);

	//imshow("dst2", dst);
	//waitKey(0);

	// eliminate small noise
	structElemEllip = getStructuringElement(MORPH_ELLIPSE, Size(updateSeL, updateSeL));
	morphologyEx(dst, dst, MORPH_OPEN, structElemEllip);

	//imshow("dst3", dst);
	//waitKey(0);
	return 0;
}
model_data::model_data(int argc,char * argv[]) : ad_comm(argc,argv)
{
		ifstream ifs( "seed.txt" ); // if this file is available
		ifs>>seed; //read in the seed
		seed += 10; // add 10 to the seed
		ofstream ofs( "seed.txt" ); //put out to seed.txt
		ofs<<seed<<endl; //the new value of the seed
  syr.allocate("syr");
  nyr.allocate("nyr");
  sage.allocate("sage");
  nage.allocate("nage");
  smon.allocate("smon");
  nmon.allocate("nmon");
  sarea.allocate("sarea");
  narea.allocate("narea");
  nations.allocate("nations");
  border.allocate(1,nations-1,"border");
  Ro.allocate("Ro");
  h.allocate("h");
  m.allocate("m");
  fe.allocate("fe");
  q.allocate("q");
  sigR.allocate("sigR");
  tau_c.allocate("tau_c");
  mo.allocate("mo");
  err.allocate("err");
  wa.allocate(sage,nage,"wa");
  fa.allocate(sage,nage,"fa");
  va.allocate(sage,nage,"va");
  minPos.allocate(sage,nage,"minPos");
  maxPos501.allocate("maxPos501");
  maxPos502.allocate("maxPos502");
  maxPossd1.allocate("maxPossd1");
  maxPossd2.allocate("maxPossd2");
  cvPos.allocate("cvPos");
  TotEffyear.allocate(1,nations,syr,nyr,"TotEffyear");
  TotEffmonth.allocate(1,nations,smon,nmon,"TotEffmonth");
  eof.allocate("eof");
		
		if( eof != 999 )
		{
			cout<<"Error reading data.\n Fix it."<<endl;
			cout<< "eof is: "<<eof<<endl;
			ad_exit(1);
		}
  age.allocate(sage,nage);
  areas.allocate(sarea,narea);
  nationareas.allocate(1,nations);
  wt.allocate(syr,nyr);
			ntstp = (nmon-smon+1) * (nyr-syr+1);
			age.fill_seqadd(sage,1);
			areas.fill_seqadd(sarea,1);
			nationareas.initialize();
			dvector natmp(1,nations);
			
			natmp(1)=sarea;
			for(int n=1; n<=nations-1; n++)
			{
				natmp(n+1)=border(n);
				for(int a=sarea;a<=narea;a++)
				{
					if(areas(a)>=natmp(n)&areas(a)<border(n))
					{
						nationareas(n)++;
					}
				}
			}
			nationareas(nations)=narea-sarea+1 - sum(nationareas(1,nations-1));
		
			random_number_generator rng(seed);
			wt.fill_randn(rng);
			wt*=sigR;
  indyr.allocate(1,ntstp);
  indmonth.allocate(1,ntstp);
  indnatarea.allocate(sarea,narea);
  pcat.allocate(1,nations);
       			int aa =0;
       			
       			for(int y=syr;y<=nyr;y++)		
       			{
       				for(int ii=smon;ii<=nmon;ii++)
       				{
       					aa++;
       					indyr(aa) = y;
       					indmonth(aa) = ii;
       				}
       			}
      		
       			ivector natmp1(1,nations+1);
       			natmp1(1) = sarea;
       			for(int n=1;n<=nations;n++)
       			{
       				natmp1(n+1)= natmp1(n)+nationareas(n);
       				for(int b = natmp1(n); b <= natmp1(n+1)-1 ; b++)
       				{
       					indnatarea(b)=n;
       				}
       			}
       			indnatarea(narea)=nations;
       			
       			pcat.initialize();
       			for(int n=1;n<=nations;n++)
       			{
       				for(int i=1;i<=ntstp;i++)
       				{
       					if(TotEffmonth(n)(indmonth(i))>0)
       					{
       						pcat(n)++;
       					}
       							
       				}
       			}
       			tot_pcat=sum(pcat);
    
       			
}
Beispiel #23
0
int main() {

//  CGAL::Timer time;
//
//  time.start();
  
  cout << "Creating point cloud" << endl;

  simu.read();

  create();
  
  if(simu.create_points()) {

    //    set_alpha_circle( Tp , 2);
    //    set_alpha_under_cos(  Tp ) ;

    cout << "Creating alpha field " << endl;
    
    set_alpha_random(  Tp ) ;

    cout << "Numbering particles " << endl;

    number(Tp);
  }
  
  // areas(Tp);
  // quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );

  // volumes(Tp, simu.FEMp() );
  // Delta(Tp);

  // linear algebra(Tp);

  // if(simu.create_points()) {
  //   nabla(Tp);
  //   Delta(Tp);
  // }
  
  move_info( Tp );

  // /// Prev test begin
  //cout << "Calculating Lapl U" << endl;
  //algebra.laplacian_v(kind::UOLD,kind::LAPLU);

  //FT dt=simu.dt();

  //cout << "Calculating Ustar implicitely" << endl;
	  //algebra.ustar_inv(kind::USTAR,  dt , kind::UOLD, false);

  //cout << "Solving PPE" << endl;
  //algebra.PPE( kind::USTAR, dt, kind:: P );

  //cout << "Calculating grad p" << endl;
  //algebra.gradient(kind::P, kind::GRADP);
  //algebra.mass_s(kind::DIVU);

  
//draw();
//  return 1;

   /// Prev test end

#ifdef WRITE
  algebra.save_matrices();
#endif

      // areas(Tp);
      // quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );

      // nabla(Tp);
      // Delta(Tp);


      // linear algebra(Tp);

      // cout << "Calculating grad alpha" << endl;
      // algebra.gradient(kind::ALPHA, kind::GRADALPHA);
  
  const std::string particle_file("particles.dat");

  draw(Tp, particle_file , true);

  simu.advance_time();
  simu.next_step();

  //  bool first_iter=true;

  CGAL::Timer time;

  time.start();

  std::ofstream log_file;

  log_file.open("main.log");

  bool is_overdamped = ( simu.mu() > 1 ) ; // high or low Re

  for(;
      simu.current_step() <= simu.Nsteps();
      simu.next_step()) {

    cout
      << "Step " << simu.current_step() 
      << " . Time " <<  simu.time()
      << " ; t step " << simu.dt()
      << endl;

    FT dt=simu.dt();

    FT dt2 = dt / 2.0 ;

    int iter=0;
    FT displ=1e10;

    FT min_displ=1e10;
    int min_iter=0;

    const int max_iter=1; //10;
    const FT  max_displ=  1e-8; // < 0 : disable

//  leapfrog, special first step.-
//    if(simu.current_step() == 1) dt2 *= 0.5;

//    dt2 *= 0.5;

    move_info(Tp);

    // iter loop
    for( ; iter<max_iter ; iter++) {

      cout << "Move iteration  " << iter << " of " << max_iter << " " << endl;

      // comment for no move.-
      displ=move( Tp , dt2 );

      cout << "Iter " << iter << " , moved avg " << displ << " to half point" << endl;

      if( (displ < max_displ) && (iter !=0) ) break;

      areas(Tp);
      quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );

      nabla(Tp);
      Delta(Tp);

      linear algebra(Tp);
      
      if( displ < min_displ) {
	min_displ=displ;
	min_iter=iter;
      }

      //      set_forces_Kolmo(Tp);

//  Reynolds number discrimination



#ifdef EXPLICIT

	cout << "Calculating Ustar explicitely" << endl;

	algebra.laplacian_v(kind::UOLD,kind::LAPLU);

	u_star(Tp, dt2 , false );

#else

//	cout << "Calculating chem pot" << endl;

//	algebra.chempot(kind::ALPHA, kind::CHEMPOT);

	cout << "Calculating alpha implicitely" << endl;

	// partly explicit ( unstable ? ):
	cout << "Calculating chem pot explicitely" << endl;

        if (iter==0)
	  algebra.chempot( kind::ALPHA0, kind::CHEMPOT );
	else
	 algebra.chempot( kind::ALPHA , kind::CHEMPOT );

	// inner iter loop

	for( int alpha_it=0 ; alpha_it < 1 ; alpha_it++) { // max_iter ; alpha_it++) {

	  cout << "Alpha loop iter " << alpha_it << endl;

	  algebra.chempot( kind::ALPHA , kind::CHEMPOT );
	  algebra.alpha_inv_cp(kind::ALPHA, dt2 , kind::ALPHA0 );

	}



	//	algebra.gradient(kind::ALPHA, kind::ALPHA0); // ???
	
	// // iterative, fully implicit (does not converge):
	
	// int alpha_it=0;
	
	//     // inner iter loop
	// for( ; alpha_it < 10 ; alpha_it++) { // max_iter ; alpha_it++) {

	//   cout << "Alpha loop iter " << alpha_it << endl;
	  
	//   algebra.alpha_inv_cp2(kind::ALPHA, dt2 , kind::ALPHA0 );
    
	//   cout << "Calculating chem pot implicitely" << endl;
	//   algebra.chempot_inv(kind::ALPHA, dt2 , kind::ALPHA0 );
	// }
	// //	draw(Tp, particle_file , true);

	
	cout << "Settinf Ustar = force" << endl;

	//	algebra.ustar_is_force(kind::USTAR);

	algebra.chem_pot_force();

	// substract spurious overall movement.-
	
	zero_mean_v( Tp , kind::FORCE);

#endif

	cout << "Solving PPE" << endl;

	// comment for no move.-
	algebra.PPE( kind::FORCE , 1 , kind:: P ); // Dt set to 1

	// cout << "Calculating grad p" << endl;
	// // comment for no move.-
	// algebra.gradient(kind::P, kind::GRADP);

	algebra.u_inv_od(kind::U);
	
	cout << "Evolving U " << endl;

	// comment for no move.-
	u_new( Tp , dt2 );

	cout << "U evolved " << endl;

    } // iter loop

    // comment for no move.-
    displ=move( Tp , dt );
    
//    update_half_velocity( Tp , false ); 

    // comment for no move.-
    update_half_velocity( Tp , is_overdamped ); 

    update_half_alpha( Tp ); 

    areas(Tp);

    quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );

    if(simu.current_step()%simu.every()==0)
      draw(Tp, particle_file , true);

    log_file
      << simu.current_step() << "  "
      <<  simu.time() << "  " ;

    integrals( Tp , log_file);     log_file << "  ";
    fidelity(  Tp , log_file );    log_file << endl;

    simu.advance_time();

  } // time loop

  time.stop();

  log_file.close();
  
  cout << "Total runtime: " << time.time() << endl;
  return 0;

}
Beispiel #24
0
Mat skinDetector::cannySegmentation(Mat img0, int minPixelSize)
{
	// Segments items in gray image (img0)
	// minPixelSize=
	// -1, returns largest region only
	// pixels, threshold for removing smaller regions, with less than minPixelSize pixels
	// 0, returns all detected segments
	
    // LB: Zero pad image to remove edge effects when getting regions....	
    int padPixels=20;
    // Rect border added at start...
    Rect tempRect;
    tempRect.x=padPixels;
    tempRect.y=padPixels;
    tempRect.width=img0.cols;
    tempRect.height=img0.rows;
    Mat img1 = Mat::zeros(img0.rows+(padPixels*2), img0.cols+(padPixels*2), CV_8UC1);
    img0.copyTo(img1(tempRect));
    
	// apply your filter
    Canny(img1, img1, 100, 200, 3); //100, 200, 3);

    // find the contours
    vector< vector<Point> > contours;
    findContours(img1, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

    // Mask for segmented regiond
    Mat mask = Mat::zeros(img1.rows, img1.cols, CV_8UC1);

    vector<double> areas(contours.size());

	if (minPixelSize==-1)
	{ // Case of taking largest region
		for(int i = 0; i < contours.size(); i++)
			areas[i] = contourArea(Mat(contours[i]));
		double max;
		Point maxPosition;
		minMaxLoc(Mat(areas),0,&max,0,&maxPosition);
		drawContours(mask, contours, maxPosition.y, Scalar(1), CV_FILLED);
	}
	else
	{ // Case for using minimum pixel size
		for (int i = 0; i < contours.size(); i++)
		{
			if (contourArea(Mat(contours[i]))>minPixelSize)
			drawContours(mask, contours, i, Scalar(1), CV_FILLED);

		}
	}
    // normalize so imwrite(...)/imshow(...) shows the mask correctly!
    normalize(mask.clone(), mask, 0.0, 255.0, CV_MINMAX, CV_8UC1);


    Mat returnMask;
    returnMask=mask(tempRect);
    
    
    // show the images
    if (verboseOutput)	imshow("Canny Skin: Img in", img0);
    if (verboseOutput)	imshow("Canny Skin: Mask", returnMask);
    if (verboseOutput)	imshow("Canny Skin: Output", img1);
    

    return returnMask;
}
Beispiel #25
0
int main() {

//  CGAL::Timer time;
//
//  time.start();
  
  cout << "Creating point cloud" << endl;

  simu.read();

  create();
  
  if(simu.create_points()) {

    //    set_alpha_circle( Tp , 2);
    //    set_alpha_under_cos(  Tp ) ;

    cout << "Creating alpha field " << endl;
    
    //    set_alpha_random(  Tp ) ; // better take it from mesh
    set_alpha_random(  Tm ) ;

    cout << "Numbering particles " << endl;

    number(Tp);
    number(Tm);
  }


  // every step
  areas(Tp);
  quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );

  // just once!
  linear algebra(Tm);

  areas(Tm);
  quad_coeffs(Tm , simu.FEMm() ); volumes(Tm, simu.FEMm() );

  cout << "Setting up diff ops " << endl;

  if(simu.create_points()) {
    nabla(Tm);
    Delta(Tm);
  }

  const std::string mesh_file("mesh.dat");
  const std::string particle_file("particles.dat");

  // step 0 draw.-
  //  draw(Tm, mesh_file     , true);
  //   draw(Tp, particle_file , true);
  
  cout << "Assigning alpha to particles " << endl;
 
#if defined FULL_FULL
  {
    Delta(Tp);
    linear algebra_p(Tp);
    from_mesh_full( Tm , Tp ,  algebra_p,kind::ALPHA);
  }
#elif defined FULL_LUMPED
  from_mesh_lumped( Tm , Tp , kind::ALPHA);
 #elif defined FLIP
  from_mesh(Tm , Tp , kind::ALPHA);
 #else
  from_mesh(Tm , Tp , kind::ALPHA);
#endif

  cout << "Moving info" << endl;
  move_info( Tm );
  move_info( Tp );

  // algebra.chempot( kind::ALPHA , kind::CHEMPOT );
  // algebra.alpha_inv_cp(kind::ALPHA, simu.dt()/2.0 , kind::ALPHA0 );

  // draw(Tm, mesh_file     , true);
  // draw(Tp, particle_file , true);

 
  // /// Prev test begin
  //cout << "Calculating Lapl U" << endl;
  //algebra.laplacian_v(kind::UOLD,kind::LAPLU);

  //FT dt=simu.dt();

  //cout << "Calculating Ustar implicitely" << endl;
	  //algebra.ustar_inv(kind::USTAR,  dt , kind::UOLD, false);

  //cout << "Solving PPE" << endl;
  //algebra.PPE( kind::USTAR, dt, kind:: P );

  //cout << "Calculating grad p" << endl;
  //algebra.gradient(kind::P, kind::GRADP);
  //algebra.mass_s(kind::DIVU);

  
//draw();
//  return 1;

   /// Prev test end

#ifdef WRITE
  algebra.save_matrices();
#endif

      // areas(Tp);
      // quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );

      // nabla(Tp);
      // Delta(Tp);


      // linear algebra(Tp);

      // cout << "Calculating grad alpha" << endl;
      // algebra.gradient(kind::ALPHA, kind::GRADALPHA);

  draw(Tm, mesh_file     , true);
  draw(Tp, particle_file , true);

  simu.advance_time();
  simu.next_step();

  //  bool first_iter=true;

  CGAL::Timer time;

  time.start();

  std::ofstream log_file;

  log_file.open("main.log");

  bool is_overdamped = ( simu.mu() > 1 ) ; // high or low Re

  for(;
      simu.current_step() <= simu.Nsteps();
      simu.next_step()) {

    cout
      << "Step " << simu.current_step() 
      << " . Time " <<  simu.time()
      << " ; t step " << simu.dt()
      << endl;

    FT dt=simu.dt();

    FT dt2 = dt / 2.0 ;

    int iter=0;
    FT displ=1e10;

    FT min_displ=1e10;
    int min_iter=0;

    const int max_iter  = 10; //10;
    const FT  max_displ = 1e-8; // < 0 : disable

//  leapfrog, special first step.-
//    if(simu.current_step() == 1) dt2 *= 0.5;

//    dt2 *= 0.5;

    move_info(Tm);
    move_info(Tp);

//     cout << "Proj alpha onto mesh " << endl;

//       //onto_mesh_lumped();
// #if defined FULL
//     onto_mesh_full( Tp , Tm , algebra, kind::ALPHA);
// #elif defined FLIP
//     flip_volumes(Tp , Tm , simu.FEMm() );
//     onto_mesh_flip(Tp,Tm,simu.FEMm(),kind::ALPHA);
// #else
//     onto_mesh_delta(Tp,Tm,kind::ALPHA);
// #endif
  
    // iter loop
    for( ; iter<max_iter ; iter++) {

      //      cout << "Projecting U from mesh " << endl;
      cout << "Projecting U , alpha0 from mesh " << endl;

#if defined FULL_FULL
      {
	Delta(Tp);
	linear algebra_p(Tp);
	from_mesh_full_v(Tm, Tp, algebra_p , kind::U);
	from_mesh_full  (Tm, Tp, algebra_p , kind::ALPHA0);
	from_mesh_full  (Tm, Tp, algebra_p , kind::ALPHA);
      }
#elif defined FULL_LUMPED
      from_mesh_lumped_v(Tm, Tp, kind::U);
      from_mesh_lumped  (Tm, Tp, kind::ALPHA0);
      from_mesh_lumped  (Tm, Tp, kind::ALPHA);
#elif defined FLIP
      from_mesh_v(Tm, Tp, kind::U);
      from_mesh  (Tm, Tp, kind::ALPHA0);
      from_mesh  (Tm, Tp, kind::ALPHA);
#else
      from_mesh_v(Tm, Tp, kind::U);
      from_mesh  (Tm, Tp, kind::ALPHA0);
      from_mesh  (Tm, Tp, kind::ALPHA);
#endif
      
      // comment for no move.-
      displ=move( Tp , dt2 );

      cout << "Iter " << iter << " , moved avg " << displ << " to half point" << endl;

      if( displ < min_displ) {
	min_displ=displ;
	min_iter=iter;
      }

      if( (displ < max_displ) && (iter !=0) ) break;

      areas(Tp);
      quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );
      
      cout << "Proj U0, alpha0 onto mesh " << endl;

#if defined FULL
      onto_mesh_full_v(Tp,Tm,algebra,kind::UOLD);
      onto_mesh_full  (Tp,Tm,algebra,kind::ALPHA0);
      onto_mesh_full  (Tp,Tm,algebra,kind::ALPHA);
#elif defined FLIP
      flip_volumes(Tp , Tm , simu.FEMm() );
      onto_mesh_flip_v(Tp,Tm,simu.FEMm(),kind::UOLD);
      onto_mesh_flip  (Tp,Tm,simu.FEMm(),kind::ALPHA0);
      onto_mesh_flip  (Tp,Tm,simu.FEMm(),kind::ALPHA);
#else
      onto_mesh_delta_v(Tp,Tm,kind::UOLD);
      onto_mesh_delta  (Tp,Tm,kind::ALPHA0);
      onto_mesh_delta  (Tp,Tm,kind::ALPHA);
#endif

     
//  Reynolds number discrimination

// #ifdef EXPLICIT

// 	cout << "Calculating Ustar explicitely" << endl;

// 	algebra.laplacian_v(kind::UOLD,kind::LAPLU);

// 	u_star(Tp, dt2 , false );

// #else

//	cout << "Calculating chem pot" << endl;

//	algebra.chempot(kind::ALPHA, kind::CHEMPOT);

//      cout << "Calculating alpha implicitely" << endl;
      //

      // partly explicit ( unstable ? ):
      cout << "Calculating chem pot explicitely" << endl;

      // inner iter loop

      for( int alpha_it=0 ; alpha_it < 1 ; alpha_it++) { // max_iter ; alpha_it++) {

	cout << "Alpha loop iter " << alpha_it << endl;
	if (iter==0)
	  algebra.chempot( kind::ALPHA0, kind::CHEMPOT );
	else
	  algebra.chempot( kind::ALPHA , kind::CHEMPOT );
	
      //	algebra.chempot( kind::ALPHA , kind::CHEMPOT );
	algebra.alpha_inv_cp(kind::ALPHA, dt2 , kind::ALPHA0 );

      }


	//	algebra.gradient(kind::ALPHA, kind::ALPHA0); // ???
	
	// // iterative, fully implicit (does not converge):
	
	// int alpha_it=0;
	
	//     // inner iter loop
	// for( ; alpha_it < 10 ; alpha_it++) { // max_iter ; alpha_it++) {

	//   cout << "Alpha loop iter " << alpha_it << endl;
	  
	//   algebra.alpha_inv_cp2(kind::ALPHA, dt2 , kind::ALPHA0 );
    
	//   cout << "Calculating chem pot implicitely" << endl;
	//   algebra.chempot_inv(kind::ALPHA, dt2 , kind::ALPHA0 );
	// }
	// //	draw(Tp, particle_file , true);
	
	cout << "Calculating Ustar implicitely" << endl;

	//	algebra.ustar_inv(kind::USTAR,  dt2 , kind::UOLD, false , false);

	// comment for no move.-
	algebra.ustar_inv_cp(kind::USTAR,  dt2 , kind::UOLD, is_overdamped , false);

	// substract spurious overall movement.-
	
	zero_mean_v( Tp , kind::USTAR);

	//#endif

	cout << "Solving PPE" << endl;

	// comment for no move.-
	algebra.PPE( kind::USTAR, dt2 , kind:: P );

	cout << "Calculating grad p" << endl;
	// comment for no move.-
	algebra.gradient(kind::P, kind::GRADP);

	cout << "Evolving U " << endl;

	// comment for no move.-
	u_new( Tm , dt2 );

	cout << "U evolved " << endl;

    } // iter loop

#if defined FULL_FULL
      {
	Delta(Tp);
	linear algebra_p(Tp);
	from_mesh_full_v(Tm, Tp, algebra_p , kind::U);
	from_mesh_full  (Tm, Tp, algebra_p , kind::ALPHA);
      }
#elif defined FULL_LUMPED
      from_mesh_lumped_v(Tm, Tp, kind::U);
      from_mesh_lumped  (Tm, Tp, kind::ALPHA);
#elif defined FLIP
      from_mesh_v(Tm, Tp, kind::U);
      from_mesh  (Tm, Tp, kind::ALPHA);
#else
      from_mesh_v(Tm, Tp, kind::U);
      from_mesh  (Tm, Tp, kind::ALPHA);
#endif

      // comment for no move.-
    displ=move( Tp , dt );
    
//    update_half_velocity( Tp , false ); 

    // comment for no move.-
    update_half_velocity( Tp , is_overdamped ); 

    update_half_alpha( Tp );  // ??????

    areas(Tp);

    quad_coeffs(Tp , simu.FEMp() ); volumes(Tp, simu.FEMp() );

    cout << "Proj U_t+1 , alpha_t+1 onto mesh " << endl;

#if defined FULL
    onto_mesh_full_v(Tp,Tm,algebra,kind::U);
    onto_mesh_full  (Tp,Tm,algebra,kind::ALPHA0);
    onto_mesh_full  (Tp,Tm,algebra,kind::ALPHA);
#elif defined FLIP
    flip_volumes(Tp , Tm , simu.FEMm() );
    onto_mesh_flip_v(Tp,Tm,simu.FEMm(),kind::U);
    onto_mesh_flip  (Tp,Tm,simu.FEMm(),kind::ALPHA0);
    onto_mesh_flip  (Tp,Tm,simu.FEMm(),kind::ALPHA);
#else
    onto_mesh_delta_v(Tp,Tm,kind::U);
    onto_mesh_delta  (Tp,Tm,kind::ALPHA);
    onto_mesh_delta  (Tp,Tm,kind::ALPHA);
#endif

    
    if(simu.current_step()%simu.every()==0) {
      draw(Tm, mesh_file     , true);
      draw(Tp, particle_file , true);
    }

    log_file
      << simu.current_step() << "  "
      <<  simu.time() << "  " ;

    // integrals( Tp , log_file);     log_file << "  ";
    // fidelity(  Tp , log_file );    log_file << endl;

    simu.advance_time();

  } // time loop

  time.stop();

  log_file.close();
  
  cout << "Total runtime: " << time.time() << endl;
  return 0;

}
void model_parameters::move_grow_die(void)
{
	dvariable tB;
	for(int i=2;i<=ntstp;i++)
	{
		//if(i>12)exit(1);
		switch (indmonth(i)) {
            case 1:           	
            	Nage(i)(sage) = (So*SB(i-nmon)/(1.+beta*SB(i-nmon)))*mfexp(wt(indyr(i))*err);
            	for(int a = sage+1;a<=nage;a++)
            	{
            		Nage(i)(a) = Nage(i-1)(a-1)*mfexp(-(m+q*Effage(i-1)(a-1)*va(a-1))/12);
            	}
            	break;
            default: 
            	Nage(i) = elem_prod(Nage(i-1),mfexp(-(m+q*elem_prod(Effage(i-1),va))/12));
            	break;
        }
		VulB(i) = elem_prod(elem_prod(Nage(i),va),wa);
		SB(i) = elem_prod(Nage(i),fa)*wa/2;
		maxPos.initialize();
		tB = Nage(i)*wa;
		calcmaxpos(tB);
		//cout<<"maxPos "<<maxPos<<endl;
		varPos = maxPos*cvPos;
		PosX(i) = minPos + (maxPos - minPos) * (0.5+0.5*sin(indmonth(i)*PI/6 - mo*PI/6)); 
		VBarea(i,sarea) = VulB(i)* (cnorm(areas(sarea)+0.5,PosX(i),varPos));
		for(int r = sarea+1;r <= narea;r++)
		{
			VBarea(i)(r) = VulB(i)* (cnorm(areas(r)+0.5,PosX(i),varPos)-cnorm(areas(r)-0.5,PosX(i),varPos));
			NAreaAge(i)(r) = elem_prod(Nage(i)(sage,nage),(cnorm(areas(r)+0.5,PosX(i),varPos)-cnorm(areas(r)-0.5,PosX(i),varPos)));
		}	
		//VBarea(i,narea) = VulB(i)* (1.0-cnorm(areas(narea)-0.5,PosX(i),varPos));
		NationVulB(i,1) = sum(VBarea(i)(sarea,sarea+nationareas(1)-1)); 
		NationVulB(i,2) = sum(VBarea(i)(sarea+nationareas(1),narea)); 
		dvar_vector tmp1(sarea,narea);
		dvar_vector tmp2(sarea,narea);
		for(int rr= sarea; rr<=narea; rr++)
		{
			tmp1(rr)= VBarea(i)(rr)/ (NationVulB(i)(indnatarea(rr)) + 1);
			tmp2(rr) = tmp1(rr)*TotEffyear(indnatarea(rr))(indyr(i));
			Effarea(i)(rr) = tmp2(rr)*TotEffmonth(indnatarea(rr))(indmonth(i));
		}
		for(int a = sage; a<=nage;a++)
		{
			dvar_vector propVBarea(sarea,narea);
			for(int rr =sarea; rr<=narea; rr++)
			{
				propVBarea(rr) = (cnorm(areas(rr)+0.5,PosX(i),varPos)-cnorm(areas(rr)-0.5,PosX(i),varPos))(a-sage+1);
				EffNatAge(indnatarea(rr))(i)(sage-2) = i;
				EffNatAge(indnatarea(rr))(i)(sage-1) = indnatarea(rr);
				EffNatAge(indnatarea(rr))(i)(a) += Effarea(i)(rr)* propVBarea(rr);
			}
			//cout<<"propVBarea "<<propVBarea<<endl;
			//cout<<"Effarea(1) "<<Effarea(1)<<endl;
			Effage(i)(a) = Effarea(i)*propVBarea;
		}
		for(int r = sarea+1;r <= narea-1;r++)
		{
			for(int a = sage; a<=nage;a++)
			{
				CatchAreaAge(i)(r)(a) = q*Effarea(i)(r)*va(a)/(q*Effarea(i)(r)*va(a)+m)*(1-mfexp(-(q*Effarea(i)(r)*va(a)+m)))*NAreaAge(i)(r)(a);
				CatchNatAge(i)(indnatarea(r))(a)+= CatchAreaAge(i)(r)(a);
			}
		}
	}
}
Beispiel #27
0
int main()
{
    {
        typedef std::piecewise_linear_distribution<> D;
        typedef D::param_type P;
        typedef std::mt19937_64 G;
        G g;
        double b[] = {10, 14, 16, 17};
        double p[] = {0, 1, 1, 0};
        const size_t Np = sizeof(p) / sizeof(p[0]) - 1;
        D d(b, b+Np+1, p);
        const int N = 1000000;
        std::vector<D::result_type> u;
        for (int i = 0; i < N; ++i)
        {
            D::result_type v = d(g);
            assert(d.min() <= v && v < d.max());
            u.push_back(v);
        }
        std::sort(u.begin(), u.end());
        int kp = -1;
        double a;
        double m;
        double bk;
        double c;
        std::vector<double> areas(Np);
        double S = 0;
        for (int i = 0; i < areas.size(); ++i)
        {
            areas[i] = (p[i]+p[i+1])*(b[i+1]-b[i])/2;
            S += areas[i];
        }
        for (int i = 0; i < areas.size(); ++i)
            areas[i] /= S;
        for (int i = 0; i < Np+1; ++i)
            p[i] /= S;
        for (int i = 0; i < N; ++i)
        {
            int k = std::lower_bound(b, b+Np+1, u[i]) - b - 1;
            if (k != kp)
            {
                a = 0;
                for (int j = 0; j < k; ++j)
                    a += areas[j];
                m = (p[k+1] - p[k]) / (b[k+1] - b[k]);
                bk = b[k];
                c = (b[k+1]*p[k] - b[k]*p[k+1]) / (b[k+1] - b[k]);
                kp = k;
            }
            assert(std::abs(f(u[i], a, m, bk, c) - double(i)/N) < .001);
        }
    }
    {
        typedef std::piecewise_linear_distribution<> D;
        typedef D::param_type P;
        typedef std::mt19937_64 G;
        G g;
        double b[] = {10, 14, 16, 17};
        double p[] = {0, 0, 1, 0};
        const size_t Np = sizeof(p) / sizeof(p[0]) - 1;
        D d(b, b+Np+1, p);
        const int N = 1000000;
        std::vector<D::result_type> u;
        for (int i = 0; i < N; ++i)
        {
            D::result_type v = d(g);
            assert(d.min() <= v && v < d.max());
            u.push_back(v);
        }
        std::sort(u.begin(), u.end());
        int kp = -1;
        double a;
        double m;
        double bk;
        double c;
        std::vector<double> areas(Np);
        double S = 0;
        for (int i = 0; i < areas.size(); ++i)
        {
            areas[i] = (p[i]+p[i+1])*(b[i+1]-b[i])/2;
            S += areas[i];
        }
        for (int i = 0; i < areas.size(); ++i)
            areas[i] /= S;
        for (int i = 0; i < Np+1; ++i)
            p[i] /= S;
        for (int i = 0; i < N; ++i)
        {
            int k = std::lower_bound(b, b+Np+1, u[i]) - b - 1;
            if (k != kp)
            {
                a = 0;
                for (int j = 0; j < k; ++j)
                    a += areas[j];
                m = (p[k+1] - p[k]) / (b[k+1] - b[k]);
                bk = b[k];
                c = (b[k+1]*p[k] - b[k]*p[k+1]) / (b[k+1] - b[k]);
                kp = k;
            }
            assert(std::abs(f(u[i], a, m, bk, c) - double(i)/N) < .001);
        }
    }
    {
        typedef std::piecewise_linear_distribution<> D;
        typedef D::param_type P;
        typedef std::mt19937_64 G;
        G g;
        double b[] = {10, 14, 16, 17};
        double p[] = {1, 0, 0, 0};
        const size_t Np = sizeof(p) / sizeof(p[0]) - 1;
        D d(b, b+Np+1, p);
        const int N = 1000000;
        std::vector<D::result_type> u;
        for (int i = 0; i < N; ++i)
        {
            D::result_type v = d(g);
            assert(d.min() <= v && v < d.max());
            u.push_back(v);
        }
        std::sort(u.begin(), u.end());
        int kp = -1;
        double a;
        double m;
        double bk;
        double c;
        std::vector<double> areas(Np);
        double S = 0;
        for (int i = 0; i < areas.size(); ++i)
        {
            areas[i] = (p[i]+p[i+1])*(b[i+1]-b[i])/2;
            S += areas[i];
        }
        for (int i = 0; i < areas.size(); ++i)
            areas[i] /= S;
        for (int i = 0; i < Np+1; ++i)
            p[i] /= S;
        for (int i = 0; i < N; ++i)
        {
            int k = std::lower_bound(b, b+Np+1, u[i]) - b - 1;
            if (k != kp)
            {
                a = 0;
                for (int j = 0; j < k; ++j)
                    a += areas[j];
                m = (p[k+1] - p[k]) / (b[k+1] - b[k]);
                bk = b[k];
                c = (b[k+1]*p[k] - b[k]*p[k+1]) / (b[k+1] - b[k]);
                kp = k;
            }
            assert(std::abs(f(u[i], a, m, bk, c) - double(i)/N) < .001);
        }
    }
    {
        typedef std::piecewise_linear_distribution<> D;
        typedef D::param_type P;
        typedef std::mt19937_64 G;
        G g;
        double b[] = {10, 14, 16};
        double p[] = {0, 1, 0};
        const size_t Np = sizeof(p) / sizeof(p[0]) - 1;
        D d(b, b+Np+1, p);
        const int N = 1000000;
        std::vector<D::result_type> u;
        for (int i = 0; i < N; ++i)
        {
            D::result_type v = d(g);
            assert(d.min() <= v && v < d.max());
            u.push_back(v);
        }
        std::sort(u.begin(), u.end());
        int kp = -1;
        double a;
        double m;
        double bk;
        double c;
        std::vector<double> areas(Np);
        double S = 0;
        for (int i = 0; i < areas.size(); ++i)
        {
            areas[i] = (p[i]+p[i+1])*(b[i+1]-b[i])/2;
            S += areas[i];
        }
        for (int i = 0; i < areas.size(); ++i)
            areas[i] /= S;
        for (int i = 0; i < Np+1; ++i)
            p[i] /= S;
        for (int i = 0; i < N; ++i)
        {
            int k = std::lower_bound(b, b+Np+1, u[i]) - b - 1;
            if (k != kp)
            {
                a = 0;
                for (int j = 0; j < k; ++j)
                    a += areas[j];
                m = (p[k+1] - p[k]) / (b[k+1] - b[k]);
                bk = b[k];
                c = (b[k+1]*p[k] - b[k]*p[k+1]) / (b[k+1] - b[k]);
                kp = k;
            }
            assert(std::abs(f(u[i], a, m, bk, c) - double(i)/N) < .001);
        }
    }
    {
        typedef std::piecewise_linear_distribution<> D;
        typedef D::param_type P;
        typedef std::mt19937_64 G;
        G g;
        double b[] = {10, 14};
        double p[] = {1, 1};
        const size_t Np = sizeof(p) / sizeof(p[0]) - 1;
        D d(b, b+Np+1, p);
        const int N = 1000000;
        std::vector<D::result_type> u;
        for (int i = 0; i < N; ++i)
        {
            D::result_type v = d(g);
            assert(d.min() <= v && v < d.max());
            u.push_back(v);
        }
        std::sort(u.begin(), u.end());
        int kp = -1;
        double a;
        double m;
        double bk;
        double c;
        std::vector<double> areas(Np);
        double S = 0;
        for (int i = 0; i < areas.size(); ++i)
        {
            areas[i] = (p[i]+p[i+1])*(b[i+1]-b[i])/2;
            S += areas[i];
        }
        for (int i = 0; i < areas.size(); ++i)
            areas[i] /= S;
        for (int i = 0; i < Np+1; ++i)
            p[i] /= S;
        for (int i = 0; i < N; ++i)
        {
            int k = std::lower_bound(b, b+Np+1, u[i]) - b - 1;
            if (k != kp)
            {
                a = 0;
                for (int j = 0; j < k; ++j)
                    a += areas[j];
                m = (p[k+1] - p[k]) / (b[k+1] - b[k]);
                bk = b[k];
                c = (b[k+1]*p[k] - b[k]*p[k+1]) / (b[k+1] - b[k]);
                kp = k;
            }
            assert(std::abs(f(u[i], a, m, bk, c) - double(i)/N) < .001);
        }
    }
    {
        typedef std::piecewise_linear_distribution<> D;
        typedef D::param_type P;
        typedef std::mt19937_64 G;
        G g;
        double b[] = {10, 14, 16, 17};
        double p[] = {25, 62.5, 12.5, 0};
        const size_t Np = sizeof(p) / sizeof(p[0]) - 1;
        D d(b, b+Np+1, p);
        const int N = 1000000;
        std::vector<D::result_type> u;
        for (int i = 0; i < N; ++i)
        {
            D::result_type v = d(g);
            assert(d.min() <= v && v < d.max());
            u.push_back(v);
        }
        std::sort(u.begin(), u.end());
        int kp = -1;
        double a;
        double m;
        double bk;
        double c;
        std::vector<double> areas(Np);
        double S = 0;
        for (int i = 0; i < areas.size(); ++i)
        {
            areas[i] = (p[i]+p[i+1])*(b[i+1]-b[i])/2;
            S += areas[i];
        }
        for (int i = 0; i < areas.size(); ++i)
            areas[i] /= S;
        for (int i = 0; i < Np+1; ++i)
            p[i] /= S;
        for (int i = 0; i < N; ++i)
        {
            int k = std::lower_bound(b, b+Np+1, u[i]) - b - 1;
            if (k != kp)
            {
                a = 0;
                for (int j = 0; j < k; ++j)
                    a += areas[j];
                m = (p[k+1] - p[k]) / (b[k+1] - b[k]);
                bk = b[k];
                c = (b[k+1]*p[k] - b[k]*p[k+1]) / (b[k+1] - b[k]);
                kp = k;
            }
            assert(std::abs(f(u[i], a, m, bk, c) - double(i)/N) < .001);
        }
    }
}
Beispiel #28
0
/*******************************************************************************
* Function:      extractFGTargets  
* Description:   extract FG targets with given conditions and return objects
* Arguments:
	inImg           -   input image
	fgImg           -   output FG mask image
	seLength        -   length of structuring elements (opening)
	threshVal       -   threshold value for converting to binary image
	minArea         -   minimum area of FG targets
	maxArea         -   maximum area of FG targets
	minAspRatio     -   minimum aspect ratio of FG targets
	maxAspRatio     -   maximum aspect ratio of FG targets
	
* Returns:       vector<FGObject>* - all extracted FG targets
* Comments:
* Revision: 
*******************************************************************************/
vector<FGObject>*
FGExtraction::extractFGTargets(InputArray inImg, OutputArray fgImg, int seLength, int threshVal, 
                                   double minArea, double maxArea, 
								   double minAspRatio, double maxAspRatio)
{
	double theta = 0.4;

	if(!inImg.obj) return NULL;

	_inImg = inImg.getMat();
	this->init();

	//showImage("inImg", _inImg);

	// background subtraction by opening
    int err = subtractBGOpenDiagonal(inImg, _bgsImg, threshVal, seLength);

	if (err>0) {
		vector<FGObject>* fgObjects = new vector<FGObject>;
		return fgObjects;
	}

	//subtractBGMedian(inImg.getMat(), bgSubImg, threshVal, seLength);
	//showImage("inImg", _inImg, 0, 1);
	//showImage("bgSub", _bgsImg);
	
    // get the contour
    vector<vector<Point>> contours = extractContours(_bgsImg);
	//cout<<contours.size()<<endl;

    // double local thresholding
    // histogram backprojection
    Mat mask = Mat::zeros(_bgsImg.size(), CV_8U); 
	vector<int> areas(contours.size());
	int cnt = 0;
	int argMax = 0;
	int max_area = 0;
    for(vector<vector<Point> >::const_iterator it = contours.begin(); it != contours.end(); ++it){
        Rect uprightBox = boundingRect(*it);
		areas[cnt] = uprightBox.height*uprightBox.width;
		if (areas[cnt]>max_area) {
			max_area = areas[cnt];
			argMax = cnt;
		}
		cnt++;
	}
	//showImage("inImg", _inImg, 0, 1);

	vector<Point> largestContour = contours[argMax];	//***** only use the largest contour
		RotatedRect orientedBox = orientedBoundingBox(largestContour);
		orientedBox.size.width *= 1.5;
        orientedBox.size.height *= 1.5;
		ellipse(mask, orientedBox, Scalar(255), -1);

		//Rect tempRect = boundingRect(largestContour);
		//Mat tempImg = mask(tempRect);
		//imshow("tempImg", tempImg);
		//imshow("mask", mask);
		//waitKey(0);

		// double local thresholding
		double percentage = 0.8;
		doubleThresholdByValue(percentage, mask);
		
		/*finish = clock();
		duration = (double)(finish - start) / (double)CLOCKS_PER_SEC;
		cout << duration << " sec" << endl;
		start = clock();*/

		// remove noise by a median filter
		medianBlur(_fgHighImg, _fgHighImg, 3);
		medianBlur(_fgLowImg, _fgLowImg, 3);
		//showImage("_fgHighImg", _fgHighImg);
		//showImage("_fgLowImg", _fgLowImg);

		/*finish = clock();
		duration = (double)(finish - start) / (double)CLOCKS_PER_SEC;
		cout << duration << " sec" << endl;
		
		start = clock();*/
		// merge two masks using histogram backprojection
		//showImage("_fgImg", _fgImg);
		//showImage("mask", mask);
		updateByHistBackproject(theta, mask);
		

		ellipse(mask, orientedBox, Scalar(0), -1);
		ellipse(_fgHighImg, orientedBox, Scalar(0), -1);
		ellipse(_fgLowImg, orientedBox, Scalar(0), -1);

    //}

	
    // thresholding by area and variance
#ifdef IMAGE_DOWNSAMPLING
	int dilateSESize = 3;
	int erodeSESize = 3;
	int varThresh = 30;
#else
	int dilateSESize = 7;
	int erodeSESize = 7;
	int varThresh = 30;
#endif

    //showImage("fg high", _fgHighImg, 0, 1);
    //showImage("fg low", _fgLowImg, 0, 1);
	//showImage("after histbp", _fgImg, 0);

	thresholdByAreaRatioVar(minArea, maxArea, dilateSESize, erodeSESize, minAspRatio, maxAspRatio, varThresh);
	
	//showImage("after area threshold", _fgImg, 0);

	// post-processing
    postProcessing(_fgImg, _fgImg);
	//imshow("_fgImg",_fgImg);
	//waitKey(0);

	// fill the holes of the fgImg
	_fgImg.copyTo(fgImg);
	floodFill(fgImg, cv::Point(0,0), Scalar(255));
	//imshow("fgImg",fgImg);
	//waitKey(0);

    bitwise_not(fgImg, fgImg);
	bitwise_or(fgImg, _fgImg, _fgImg);
	//imshow("inImg", inImg);
	//imshow("_fgImg",_fgImg);
	//waitKey(0);

	// opening
	RotatedRect rotatedR = fitEllipse(Mat(largestContour));
	float objHeight = min(rotatedR.size.height,rotatedR.size.width);
	int seSize = int(objHeight/10.0+0.5);
	
	Mat se = getStructuringElement(MORPH_ELLIPSE, Size(seSize, seSize));		//***** choose different size according to object height
	morphologyEx(_fgImg, _fgImg, MORPH_OPEN, se);

	//imshow("_fgImg",_fgImg);
	//waitKey(0);


	// close
	morphologyEx(_fgImg, _fgImg, MORPH_CLOSE, se);

	// timer
	/*clock_t start, finish;
	double duration = 0.0;
	start = clock();

	finish = clock();
	duration = (double)(finish - start) / (double)CLOCKS_PER_SEC;
	cout << duration << " sec" << endl;*/

	thresholdByAreaRatioVar(0.5*minArea, maxArea, 1, 1, minAspRatio, maxAspRatio, 30);

	// push targets into our vector
	//Mat largeInImg;
#ifdef IMAGE_DOWNSAMPLING
	resize(_fgImg, _fgImg, Size(), 2, 2, INTER_LINEAR);
	resize(_inImg, largeInImg, Size(), 2, 2, INTER_LINEAR);
#endif
	//tempImg = _fgImg.clone(); 
	//findContours(tempImg, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
	//tempImg.release();

	//imshow("_fgImg",_fgImg);
	//waitKey(0);
	contours = extractContours(_fgImg);

	vector<FGObject>* fgObjects = new vector<FGObject>;
	//Mat mask8U = Mat::zeros(largeInImg.size(), CV_8U); 
	for (size_t i = 0; i < contours.size(); i++){
		double area = contourArea(contours[i]);
		RotatedRect orientedRect = orientedBoundingBox(contours[i]);
		Point2f points[4];
		orientedRect.points(points);
		/*
		orientedRect.size.width *= 1.5;
        orientedRect.size.height *= 1.5;
		ellipse(mask8U, orientedRect, Scalar(255), -1);
		
		int channels[] = {0};
		int nbins = 16;
		const int histSize[] = {nbins};
		float range[] = {0, 255};
		const float* ranges[] = {range};
		Mat hist;
		cv::calcHist(&largeInImg, 1, channels, mask8U, hist, 1, histSize, ranges);
		*/
		// push targets into our vector
		FGObject* obj = new FGObject;
		//obj->histogram = hist;
		obj->setObjectProperties(area, orientedRect.angle, contours[i], points, SOURCE_UNRECTIFIED);

		if(obj->isPartialOut(_fgImg.cols, _fgImg.rows) == false){
			fgObjects->push_back(*obj);
		}
		delete obj;

		//ellipse(mask8U, orientedRect, Scalar(0), -1);
		
	}

	//  eliminate artifacts with width of 1 at the border...
	rectangle(_fgImg, Point(0,0), Point(_fgImg.cols-1, _fgImg.rows-1), Scalar(0));
	
	fgImg.getMatRef() = _fgImg.clone();
	return fgObjects;
}
int main (int argc, char* argv[])
{
	ApplicationsLib::LogogSetup logog_setup;

	TCLAP::CmdLine cmd("Computes ids of mesh nodes that are in polygonal "
		"regions and resides on the top surface. The polygonal regions have to "
		"be given in a gml- or gli-file. The found mesh nodes and the associated"
		" area are written as txt and csv data."
		"The documentation is available at https://docs.opengeosys.org/docs/tools/model-preparation/computesurfacenodeidsinpolygonalregion",
		' ',
		"0.1");
	TCLAP::ValueArg<std::string> mesh_in("m", "mesh-input-file",
		"the name of the file containing the input mesh", true,
		"", "file name of input mesh");
	cmd.add(mesh_in);
	TCLAP::ValueArg<std::string> geo_in("g", "geo-file",
		"the name of the gml file containing the polygons", true,
		"", "file name of input geometry");
	cmd.add(geo_in);

	cmd.parse(argc, argv);

	std::unique_ptr<MeshLib::Mesh const> mesh(FileIO::readMeshFromFile(mesh_in.getValue()));
	INFO("Mesh read: %u nodes, %u elements.", mesh->getNNodes(), mesh->getNElements());

	GeoLib::GEOObjects geo_objs;
	FileIO::readGeometryFromFile(geo_in.getValue(), geo_objs);
	std::vector<std::string> geo_names;
	geo_objs.getGeometryNames(geo_names);
	INFO("Geometry \"%s\" read: %u points, %u polylines.",
		geo_names[0].c_str(),
		geo_objs.getPointVec(geo_names[0])->size(),
		geo_objs.getPolylineVec(geo_names[0])->size());

	MathLib::Vector3 const dir(0.0, 0.0, -1.0);
	double angle(90);

	auto computeElementTopSurfaceAreas = [](MeshLib::Mesh const& mesh,
		MathLib::Vector3 const& d, double angle)
	{
		std::unique_ptr<MeshLib::Mesh> surface_mesh(
			MeshLib::MeshSurfaceExtraction::getMeshSurface(mesh, d, angle));
		return MeshLib::MeshSurfaceExtraction::getSurfaceAreaForNodes(
			*surface_mesh.get());
	};

	std::vector<double> areas(computeElementTopSurfaceAreas(*mesh, dir, angle));
	std::vector<GeoLib::Point*> all_sfc_pnts(
		MeshLib::MeshSurfaceExtraction::getSurfaceNodes(*mesh, dir, angle)
	);

	std::for_each(all_sfc_pnts.begin(), all_sfc_pnts.end(), [](GeoLib::Point* p) { (*p)[2] = 0.0; });

	std::vector<MeshLib::Node*> const& mesh_nodes(mesh->getNodes());
	GeoLib::PolylineVec const* ply_vec(
		geo_objs.getPolylineVecObj(geo_names[0])
	);
	std::vector<GeoLib::Polyline*> const& plys(*(ply_vec->getVector()));

	for (std::size_t j(0); j<plys.size(); j++) {
		if (! plys[j]->isClosed()) {
			continue;
		}
		std::string polygon_name;
		ply_vec->getNameOfElement(plys[j], polygon_name);
		if (polygon_name.empty())
			polygon_name = "Polygon-" + std::to_string(j);
		// create Polygon from Polyline
		GeoLib::Polygon const& polygon(*(plys[j]));
		// ids of mesh nodes on surface that are within the given polygon
		std::vector<std::pair<std::size_t, double>> ids_and_areas;
		for (std::size_t k(0); k<all_sfc_pnts.size(); k++) {
			GeoLib::Point const& pnt(*(all_sfc_pnts[k]));
			if (polygon.isPntInPolygon(pnt)) {
				ids_and_areas.push_back(std::make_pair(pnt.getID(), areas[k]));
			}
		}
		if (ids_and_areas.empty()) {
			ERR("Polygonal part of surface \"%s\" doesn't contains nodes. No "
				"output will be generated.", polygon_name.c_str());
			continue;
		}

		std::string const out_path(BaseLib::extractPath(geo_in.getValue()));
		std::string id_and_area_fname(out_path + polygon_name);
		std::string csv_fname(out_path + polygon_name);
		id_and_area_fname += std::to_string(j) + ".txt";
		csv_fname += std::to_string(j) + ".csv";
		INFO("Polygonal part of surface \"%s\" contains %ul nodes. Writting to"
			" files \"%s\" and \"%s\".",
			polygon_name.c_str(),
			ids_and_areas.size(),
			id_and_area_fname.c_str(),
			csv_fname.c_str()
		);
		writeToFile(id_and_area_fname, csv_fname, ids_and_areas, mesh_nodes);
	}

	std::for_each(all_sfc_pnts.begin(), all_sfc_pnts.end(), std::default_delete<GeoLib::Point>());

	return 0;
}
int main (int argc, char* argv[])
{
    ApplicationsLib::LogogSetup logog_setup;

    TCLAP::CmdLine cmd("The tool computes the area per node of the surface mesh"
        " and writes the information as txt and csv data.", ' ', "0.1");
    TCLAP::ValueArg<std::string> mesh_in("i", "mesh-input-file",
        "the name of the file containing the input mesh", true,
        "", "file name of input mesh");
    cmd.add(mesh_in);
    TCLAP::ValueArg<std::string> id_prop_name("", "id-prop-name",
        "the name of the property containing the id information", false,
        "OriginalSubsurfaceNodeIDs", "property name");
    cmd.add(id_prop_name);
    TCLAP::ValueArg<std::string> out_base_fname("p", "output-base-name",
        "the path and base file name the output will be written to", false,
        "", "output path and base name as one string");
    cmd.add(out_base_fname);

    cmd.parse(argc, argv);

    std::unique_ptr<MeshLib::Mesh> surface_mesh(
        MeshLib::IO::readMeshFromFile(mesh_in.getValue()));
    INFO("Mesh read: %u nodes, %u elements.", surface_mesh->getNNodes(),
         surface_mesh->getNElements());
    // ToDo check if mesh is read correct and if the mesh is a surface mesh

    // check if a node property containing the subsurface ids is available
    boost::optional<MeshLib::PropertyVector<std::size_t> const&> orig_node_ids(
        surface_mesh->getProperties().getPropertyVector<std::size_t>(
            id_prop_name.getValue()));
    // if the node property is not available generate it
    if (!orig_node_ids) {
        boost::optional<MeshLib::PropertyVector<std::size_t>&> node_ids(
            surface_mesh->getProperties().createNewPropertyVector<std::size_t>(
                id_prop_name.getValue(), MeshLib::MeshItemType::Node, 1));
        if (!node_ids) {
            ERR("Fatal error: could not create property.");
            return EXIT_FAILURE;
        }
        node_ids->resize(surface_mesh->getNNodes());
        std::iota(node_ids->begin(), node_ids->end(), 0);
        orig_node_ids = node_ids;
    }

    std::vector<double> areas(
        MeshLib::MeshSurfaceExtraction::getSurfaceAreaForNodes(*surface_mesh));

    // pack area and node id together
    std::vector<std::pair<std::size_t, double>> ids_and_areas;
    std::transform(orig_node_ids->cbegin(), orig_node_ids->cend(),
                   areas.cbegin(), std::back_inserter(ids_and_areas),
                   std::make_pair<std::size_t const&, double const&>);

    // generate file names for output
    std::string path(out_base_fname.getValue());
    if (path.empty())
        path = BaseLib::dropFileExtension(mesh_in.getValue());
    std::string const id_and_area_fname(path+".txt");
    std::string const csv_fname(path+".csv");

    writeToFile(id_and_area_fname, csv_fname, ids_and_areas,
                surface_mesh->getNodes());

    return EXIT_SUCCESS;
}