Ejemplo n.º 1
0
inline
Point2
midpoint2(const Point2 &p, const Point2 &q)
{
  // return Point2((p.x_ref() + q.x_ref())/FT(2),(p.y_ref() + q.y_ref())/FT(2));
  return Point2((p.x() + q.x())/FT(2), (p.y() + q.y())/FT(2));
}
Ejemplo n.º 2
0
double single_file_correlate(std::string directory, std::string fname,rarray<double,1> predictPS){
  // Read in detection signal, do the Fourier transform and compute the power spectrum
  data_cols detection = readcols(directory,fname);
  rarray<std::complex<double>,1> detection_FT = FT(detection.signal);
  rarray<double,1> detectPS = powerspectrum(detection_FT);                             
  return correlation_coeffecient(predictPS,detectPS);
}
void Scene_polyhedron_shortest_path_item::remove_nearest_point(const Face_location& faceLocation)
{
  Surface_mesh_shortest_path_traits::Compute_squared_distance_3 computeSquaredDistance3;
  
  const Point_3 pickLocation = m_shortestPaths->point(faceLocation.first, faceLocation.second);
  
  Surface_mesh_shortest_path::Source_point_iterator found = m_shortestPaths->source_points_end();
  FT minDistance(0.0);
  const FT thresholdDistance = FT(0.4);
  
  for (Surface_mesh_shortest_path::Source_point_iterator it = m_shortestPaths->source_points_begin(); it != m_shortestPaths->source_points_end(); ++it)
  {
    Point_3 sourceLocation = m_shortestPaths->point(it->first, it->second);
    FT distance = computeSquaredDistance3(sourceLocation, pickLocation);
    
    if ((found == m_shortestPaths->source_points_end() && distance <= thresholdDistance) || distance < minDistance)
    {
      found = it;
      minDistance = distance;
    }
  }
  
  if (found != m_shortestPaths->source_points_end())
  {
    m_shortestPaths->remove_source_point(found);
  }
}
Ejemplo n.º 4
0
FT Scene::bbox_diag() const
{
    double dx = m_bbox.xmax()-m_bbox.xmin();
    double dy = m_bbox.ymax()-m_bbox.ymin();
    double dz = m_bbox.zmax()-m_bbox.zmin();

    return FT(std::sqrt(dx*dx + dy*dy + dz*dz));
}
Ejemplo n.º 5
0
void Scene::compute_distance_function(const Tree& tree)
{
    // Get transformation
    Aff_transformation t = frame_transformation();

    m_max_distance_function = FT(0);
    FT diag = bbox_diag();

    const FT dx = diag;
    const FT dy = diag;
    const FT z (0);

    for(int i=0 ; i<m_grid_size ; ++i)
    {
        FT x = -diag/FT(2) + FT(i)/FT(m_grid_size) * dx;

        for(int j=0 ; j<m_grid_size ; ++j)
        {
            FT y = -diag/FT(2) + FT(j)/FT(m_grid_size) * dy;

            Point query = t( Point(x,y,z) );
            FT dist = CGAL::sqrt( tree.squared_distance(query) );

            m_distance_function[i][j] = Point_distance(query,dist);
            m_max_distance_function = (std::max)(dist, m_max_distance_function);
        }
    }
}
void LowMachNavierStokesSPGSMStabilization<Mu,SH,TC>::assemble_energy_mass_residual( bool /*compute_jacobian*/,
        AssemblyContext& context )
{
    // The number of local degrees of freedom in each variable.
    const unsigned int n_T_dofs = context.get_dof_indices(this->_temp_vars.T()).size();

    // Element Jacobian * quadrature weights for interior integration.
    const std::vector<libMesh::Real> &JxW =
        context.get_element_fe(this->_temp_vars.T())->get_JxW();

    // The temperature shape functions gradients at interior quadrature points.
    const std::vector<std::vector<libMesh::RealGradient> >& T_gradphi =
        context.get_element_fe(this->_temp_vars.T())->get_dphi();

    libMesh::DenseSubVector<libMesh::Number> &FT = context.get_elem_residual(this->_temp_vars.T()); // R_{T}

    unsigned int n_qpoints = context.get_element_qrule().n_points();

    for (unsigned int qp=0; qp != n_qpoints; qp++)
    {
        libMesh::Number u, v;
        u = context.fixed_interior_value(this->_flow_vars.u(), qp);
        v = context.fixed_interior_value(this->_flow_vars.v(), qp);

        libMesh::Gradient grad_T = context.fixed_interior_gradient(this->_temp_vars.T(), qp);

        libMesh::NumberVectorValue U(u,v);
        if (this->mesh_dim(context) == 3)
            U(2) = context.fixed_interior_value(this->_flow_vars.w(), qp); // w

        libMesh::Real T = context.fixed_interior_value( this->_temp_vars.T(), qp );
        libMesh::Real rho = this->rho( T, this->get_p0_transient( context, qp ) );

        libMesh::Real k = this->_k(T);
        libMesh::Real cp = this->_cp(T);

        libMesh::Number rho_cp = rho*this->_cp(T);

        libMesh::FEBase* fe = context.get_element_fe(this->_flow_vars.u());

        libMesh::RealGradient g = this->_stab_helper.compute_g( fe, context, qp );
        libMesh::RealTensor G = this->_stab_helper.compute_G( fe, context, qp );

        libMesh::Real tau_E = this->_stab_helper.compute_tau_energy( context, qp, g, G, rho, U, k, cp, false );

        libMesh::Real RE_t = this->compute_res_energy_transient( context, qp );

        for (unsigned int i=0; i != n_T_dofs; i++)
        {
            FT(i) -= rho_cp*tau_E*RE_t*U*T_gradphi[i][qp]*JxW[qp];
        }

    }

    return;
}
Ejemplo n.º 7
0
void create(Triangulation& Tp) {

  int N=simu.no_of_particles();
  std::vector<Point> points;
  //  points.reserve(N);

  if(simu.create_points()) {
    if(simu.at_random()) {
      points.reserve(N);

      CGAL::Random_points_in_square_2<Point,Creator> g(LL/2.0-0.0001);
      CGAL::cpp11::copy_n( g, N, std::back_inserter(points));


      cout << N << "  particles placed at random" << endl;
    } else {
      // if((plotting)&&(Nin%2==0)&&(spike)) {
      // 	cout << "Please enter an odd number of particles" << endl;
      // 	std::abort();
      // }

      int Nb=sqrt(N + 1e-12);

      N=Nb*Nb;

      simu.set_no_of_particles(N);

      points.reserve(N);
      cout << N << " particles placed on square lattice" << endl;

      FT spacing=LL/FT(Nb+0);
      FT side=LL-1*spacing;

      points_on_square_grid_2(side/2.0, N, std::back_inserter(points),Creator());;

      //      for(int i = 0 ; i < Nb ; ++i )
	
      
      if(simu.perturb()) {
	CGAL::perturb_points_2(
			       points.begin(), points.end(),
			       simu.pert_rel()* spacing );//,Creator());
	cout << "each particle perturbed about " << simu.pert_rel()* spacing  << endl;
      }

    }

   }

    cout << "Inserting" << endl;

    Tp.insert(points.begin(), points.end());

    return;

}
Ejemplo n.º 8
0
void number(Triangulation& T) {

  int idx=0;

  int N=simu.no_of_particles();

  int Nb=sqrt(N + 1e-12);
    
  FT spacing=LL/FT(Nb+0);
  FT side=LL-1*spacing;

  
  for(F_v_it vit=T.vertices_begin();
      vit != T.vertices_end();
      vit++) {
    //    vit->indx.set(i); //or
    vit->idx = idx;

    FT x = vit->point().x() + side/2.0;
    FT y = vit->point().y() + side/2.0;

    int i = rint(  FT(Nb) * x / LL );//+ 0.5);
    int j = rint(  FT(Nb) * y / LL );//+ 0.5);

    //    --i; --j;
    
    vit->nx = i;
    vit->ny = j;

    // cout << idx
    // 	 << "  " << i
    //   	 << "  " << j
    //   	 << "  " << x
    //   	 << "  " << y
    // 	 << endl;


    ++idx;

  }

  return;
}
Ejemplo n.º 9
0
  void BunsenSource::element_time_derivative( bool /*compute_jacobian*/,
					      GRINS::AssemblyContext& context,
					      GRINS::CachedValues& /*cache*/ )
  {
#ifdef GRINS_USE_GRVY_TIMERS
    this->_timer->BeginTimer("BunsenSource::element_time_derivative");
#endif
  
    // The number of local degrees of freedom in each variable.
    const unsigned int n_T_dofs = context.get_dof_indices(_T_var).size();

    // Element Jacobian * quadrature weights for interior integration.
    const std::vector<libMesh::Real> &JxW =
      context.get_element_fe(_T_var)->get_JxW();

    // The temperature shape functions at interior quadrature points.
    const std::vector<std::vector<libMesh::Real> >& T_phi =
      context.get_element_fe(_T_var)->get_phi();

    // Locations of quadrature points
    const std::vector<libMesh::Point>& x_qp = context.get_element_fe(_T_var)->get_xyz();

    // Get residuals
    libMesh::DenseSubVector<libMesh::Number> &FT = context.get_elem_residual(_T_var); // R_{T}

    // Now we will build the element Jacobian and residual.
    // Constructing the residual requires the solution and its
    // gradient from the previous timestep.  This must be
    // calculated at each quadrature point by summing the
    // solution degree-of-freedom values by the appropriate
    // weight functions.
    unsigned int n_qpoints = context.get_element_qrule().n_points();
    
    for (unsigned int qp=0; qp != n_qpoints; qp++)
      {
	const libMesh::Real r = x_qp[qp](0);
	const libMesh::Real z = x_qp[qp](1);
	
	if( r <= _r_max &&
	    z >= _z_min &&
	    z <= _z_max )
	  {
	    for (unsigned int i=0; i != n_T_dofs; i++)
	      {
		FT(i) += _value*T_phi[i][qp]*r*JxW[qp];
	      }
	  }
      }

#ifdef GRINS_USE_GRVY_TIMERS
    this->_timer->EndTimer("BunsenSource::element_time_derivative");
#endif

    return;
  }
void Scene_polyhedron_shortest_path_item::get_as_vertex_point(Scene_polyhedron_shortest_path_item::Face_location& inOutLocation)
{
  size_t maxIndex = 0;
  FT maxCoord(inOutLocation.second[0]);
  
  for (size_t i = 1; i < 3; ++i)
  {
    if (inOutLocation.second[i] > maxCoord)
    {
      maxIndex = i;
      maxCoord = inOutLocation.second[i];
    }
  }
  
  FT coords[3] = { FT(0.0), FT(0.0), FT(0.0), };
  coords[maxIndex] = FT(1.0);
  
  Construct_barycentric_coordinate construct_barycentric_coordinate;
  inOutLocation.second = construct_barycentric_coordinate(coords[0], coords[1], coords[2]);
}
Ejemplo n.º 11
0
  void LowMachNavierStokes<Mu,SH,TC>::assemble_energy_time_deriv( bool /*compute_jacobian*/,
								  AssemblyContext& context,
								  CachedValues& cache )
  {
    // The number of local degrees of freedom in each variable.
    const unsigned int n_T_dofs = context.get_dof_indices(this->_T_var).size();

    // Element Jacobian * quadrature weights for interior integration.
    const std::vector<libMesh::Real> &JxW =
      context.get_element_fe(this->_T_var)->get_JxW();

    // The temperature shape functions at interior quadrature points.
    const std::vector<std::vector<libMesh::Real> >& T_phi =
      context.get_element_fe(this->_T_var)->get_phi();

    // The temperature shape functions gradients at interior quadrature points.
    const std::vector<std::vector<libMesh::RealGradient> >& T_gradphi =
      context.get_element_fe(this->_T_var)->get_dphi();

    libMesh::DenseSubVector<libMesh::Number> &FT = context.get_elem_residual(this->_T_var); // R_{T}

    unsigned int n_qpoints = context.get_element_qrule().n_points();
    for (unsigned int qp=0; qp != n_qpoints; qp++)
      {
	libMesh::Number u, v, T, p0;
	u = cache.get_cached_values(Cache::X_VELOCITY)[qp];
	v = cache.get_cached_values(Cache::Y_VELOCITY)[qp];
	T = cache.get_cached_values(Cache::TEMPERATURE)[qp];
	p0 = cache.get_cached_values(Cache::THERMO_PRESSURE)[qp];

	libMesh::Gradient grad_T = cache.get_cached_gradient_values(Cache::TEMPERATURE_GRAD)[qp];

	libMesh::NumberVectorValue U(u,v);
	if (this->_dim == 3)
	  U(2) = cache.get_cached_values(Cache::Z_VELOCITY)[qp]; // w

	libMesh::Number k = this->_k(T);
	libMesh::Number cp = this->_cp(T);

	libMesh::Number rho = this->rho( T, p0 );

	// Now a loop over the pressure degrees of freedom.  This
	// computes the contributions of the continuity equation.
	for (unsigned int i=0; i != n_T_dofs; i++)
	  {
	    FT(i) += ( -rho*cp*U*grad_T*T_phi[i][qp] // convection term
		       - k*grad_T*T_gradphi[i][qp]            // diffusion term
		       )*JxW[qp]; 
	  }
      }

    return;
  }
Ejemplo n.º 12
0
  void HeatTransferSPGSMStabilization<K>::element_time_derivative
  ( bool compute_jacobian, AssemblyContext & context )
  {
    // The number of local degrees of freedom in each variable.
    const unsigned int n_T_dofs = context.get_dof_indices(this->_temp_vars.T()).size();

    // Element Jacobian * quadrature weights for interior integration.
    const std::vector<libMesh::Real> &JxW =
      context.get_element_fe(this->_temp_vars.T())->get_JxW();

    const std::vector<std::vector<libMesh::RealGradient> >& T_gradphi =
      context.get_element_fe(this->_temp_vars.T())->get_dphi();

    libMesh::DenseSubVector<libMesh::Number> &FT = context.get_elem_residual(this->_temp_vars.T()); // R_{T}

    libMesh::FEBase* fe = context.get_element_fe(this->_temp_vars.T());

    unsigned int n_qpoints = context.get_element_qrule().n_points();

    for (unsigned int qp=0; qp != n_qpoints; qp++)
      {
        libMesh::RealGradient g = this->_stab_helper.compute_g( fe, context, qp );
        libMesh::RealTensor G = this->_stab_helper.compute_G( fe, context, qp );

        libMesh::RealGradient U( context.interior_value( this->_flow_vars.u(), qp ),
                                 context.interior_value( this->_flow_vars.v(), qp ) );
        if( this->_flow_vars.dim() == 3 )
          {
            U(2) = context.interior_value( this->_flow_vars.w(), qp );
          }

        // Compute Conductivity at this qp
        libMesh::Real _k_qp = this->_k(context, qp);

        libMesh::Real tau_E = this->_stab_helper.compute_tau_energy( context, G, this->_rho, this->_Cp, _k_qp,  U, this->_is_steady );

        libMesh::Real RE_s = this->_stab_helper.compute_res_energy_steady( context, qp, this->_rho, this->_Cp, _k_qp );

        for (unsigned int i=0; i != n_T_dofs; i++)
          {
            FT(i) += -tau_E*RE_s*this->_rho*this->_Cp*U*T_gradphi[i][qp]*JxW[qp];
          }

        if( compute_jacobian )
          {
            libmesh_not_implemented();
          }

      }
  }
Ejemplo n.º 13
0
void barycentric(const Point &p,
		 const Point &a,
		 const Point &b,
		 const Point &c,
		 FT &u, FT &v, FT &w)
{
  auto v0 = b - a, v1 = c - a, v2 = p - a;
  FT d00 = v0*v0;
  FT d01 = v0*v1;
  FT d11 = v1*v1;
  FT d20 = v2*v0;
  FT d21 = v2*v1;
  FT denom = d00 * d11 - d01 * d01;
  v = (d11 * d20 - d01 * d21) / denom;
  w = (d00 * d21 - d01 * d20) / denom;
  u = FT(1) - v - w;
}
void Scene_polyhedron_shortest_path_item::get_as_edge_point(Scene_polyhedron_shortest_path_item::Face_location& inOutLocation)
{
  size_t minIndex = 0;
  FT minCoord(inOutLocation.second[0]);
  
  for (size_t i = 1; i < 3; ++i)
  {
    if (minCoord > inOutLocation.second[i])
    {
      minIndex = i;
      minCoord = inOutLocation.second[i];
    }
  }
  
  // The nearest edge is that of the two non-minimal barycentric coordinates
  size_t nearestEdge[2];
  size_t current = 0;
  
  for (size_t i = 0; i < 3; ++i)
  {
    if (i != minIndex)
    {
      nearestEdge[current] = i;
      ++current;
    }
  }

  Construct_barycentric_coordinate construct_barycentric_coordinate;

  Point_3 trianglePoints[3] = { 
    m_shortestPaths->point(inOutLocation.first, construct_barycentric_coordinate(FT(1.0), FT(0.0), FT(0.0))),
    m_shortestPaths->point(inOutLocation.first, construct_barycentric_coordinate(FT(0.0), FT(1.0), FT(0.0))),
    m_shortestPaths->point(inOutLocation.first, construct_barycentric_coordinate(FT(0.0), FT(0.0), FT(1.0))),
  };
  
  CGAL::Surface_mesh_shortest_paths_3::Parametric_distance_along_segment_3<Surface_mesh_shortest_path_traits> parametricDistanceSegment3;
  
  Point_3 trianglePoint = m_shortestPaths->point(inOutLocation.first, inOutLocation.second);
  
  FT distanceAlongSegment = parametricDistanceSegment3(trianglePoints[nearestEdge[0]], trianglePoints[nearestEdge[1]], trianglePoint);
  
  FT coords[3] = { FT(0.0), FT(0.0), FT(0.0), };
  
  coords[nearestEdge[1]] = distanceAlongSegment;
  coords[nearestEdge[0]] = FT(1.0) - distanceAlongSegment;

  inOutLocation.second = construct_barycentric_coordinate(coords[0], coords[1], coords[2]);
}
Ejemplo n.º 15
0
//============================================================
void im_complex::SlowFT()
{
   // Calculate Slow 1D FT
   int ydim = Re.Ydim;
   int xdim = Re.Xdim;
   if ((ydim == 1) && (xdim > 1))
   {
      FT();
   }

   // Calculate Slow 2D FT
   else if ((ydim > 1) && (xdim > 1))
   {
      // Copy input image
      im_complex image(xdim, ydim);
      Swap(image);
      for (int v = 0; v < ydim; v++)
	 for (int u = 0; u < xdim; u++)
	 {
	    Re.Data2D[v][u] = 0;
	    Im.Data2D[v][u] = 0;
	    double u_angle = u * 2 * M_PI / xdim;
	    double v_angle = v * 2 * M_PI / ydim;
	    for (int y = 0; y < ydim; y++)
	       for (int x = 0; x < xdim; x++)
	       {
		  // Positive angle for FT
		  double angle = x * u_angle + y * v_angle;
		  double cos_angle = cos(angle);
		  double sin_angle = sin(angle);
		  Re.Data2D[v][u] += image.Re.Data2D[y][x] * cos_angle
		     - image.Im.Data2D[y][x] * sin_angle;
		  Im.Data2D[v][u] += image.Re.Data2D[y][x] * sin_angle
		     + image.Im.Data2D[y][x] * cos_angle;
	       }
	    Re.Data2D[v][u] /= xdim * ydim;
	    Im.Data2D[v][u] /= xdim * ydim;
	 }
   }
}
Ejemplo n.º 16
0
 FT operator-(const FT)const{return FT();}
Ejemplo n.º 17
0
 FT operator*(FT)const{return FT();}
Ejemplo n.º 18
0
float
RandomNoise::operator()(SmoothType smooth,int subseed,float xf,float yf,float tf,int loop)const
{
	int x((int)floor(xf));
	int y((int)floor(yf));
	int t((int)floor(tf));
	int t_1, t0, t1, t2;

	if (loop)
	{
		t0  = t % loop;	if (t0  <  0   ) t0  += loop;
		t_1 = t0 - 1;	if (t_1 <  0   ) t_1 += loop;
		t1  = t0 + 1;	if (t1  >= loop) t1  -= loop;
		t2  = t1 + 1;	if (t2  >= loop) t2  -= loop;
	}
	else
	{
		t0  = t;
		t_1 = t - 1;
		t1  = t + 1;
		t2  = t + 2;
	}

	// synfig::info("%s:%d tf %.2f loop %d fraction %.2f ( -1,0,1,2 : %2d %2d %2d %2d)", __FILE__, __LINE__, tf, loop, tf-t, t_1, t0, t1, t2);

	switch(smooth)
	{
	case SMOOTH_CUBIC:	// cubic
		{
			#define f(j,i,k)	((*this)(subseed,i,j,k))
			//Using catmull rom interpolation because it doesn't blur at all
			// ( http://www.gamedev.net/reference/articles/article1497.asp )
			//bezier curve with intermediate ctrl pts: 0.5/3(p(i+1) - p(i-1)) and similar
			float xfa [4], tfa[4];

			//precalculate indices (all clamped) and offset
			const int xa[] = {x-1,x,x+1,x+2};
			const int ya[] = {y-1,y,y+1,y+2};
			const int ta[] = {t_1,t0,t1,t2};

			const float dx(xf-x);
			const float dy(yf-y);
			const float dt(tf-t);

			//figure polynomials for each point
			const float txf[] =
			{
				0.5f*dx*(dx*(dx*(-1.f) + 2.f) - 1.f),	//-t + 2t^2 -t^3
				0.5f*(dx*(dx*(3.f*dx - 5.f)) + 2.f), 	//2 - 5t^2 + 3t^3
				0.5f*dx*(dx*(-3.f*dx + 4.f) + 1.f),		//t + 4t^2 - 3t^3
				0.5f*dx*dx*(dx-1.f)						//-t^2 + t^3
			};

			const float tyf[] =
			{
				0.5f*dy*(dy*(dy*(-1.f) + 2.f) - 1.f),	//-t + 2t^2 -t^3
				0.5f*(dy*(dy*(3.f*dy - 5.f)) + 2.f), 	//2 - 5t^2 + 3t^3
				0.5f*dy*(dy*(-3.f*dy + 4.f) + 1.f),		//t + 4t^2 - 3t^3
				0.5f*dy*dy*(dy-1.f)						//-t^2 + t^3
			};

			const float ttf[] =
			{
				0.5f*dt*(dt*(dt*(-1.f) + 2.f) - 1.f),	//-t + 2t^2 -t^3
				0.5f*(dt*(dt*(3.f*dt - 5.f)) + 2.f), 	//2 - 5t^2 + 3t^3
				0.5f*dt*(dt*(-3.f*dt + 4.f) + 1.f),		//t + 4t^2 - 3t^3
				0.5f*dt*dt*(dt-1.f)						//-t^2 + t^3
			};

			//evaluate polynomial for each row
			for(int i = 0; i < 4; ++i)
			{
				for(int j = 0; j < 4; ++j)
				{
					tfa[j] = f(ya[i],xa[j],ta[0])*ttf[0] + f(ya[i],xa[j],ta[1])*ttf[1] + f(ya[i],xa[j],ta[2])*ttf[2] + f(ya[i],xa[j],ta[3])*ttf[3];
				}
				xfa[i] = tfa[0]*txf[0] + tfa[1]*txf[1] + tfa[2]*txf[2] + tfa[3]*txf[3];
			}

			//return the cumulative column evaluation
			return xfa[0]*tyf[0] + xfa[1]*tyf[1] + xfa[2]*tyf[2] + xfa[3]*tyf[3];
#undef f
		}
		break;


	case SMOOTH_FAST_SPLINE:	// Fast Spline (non-animated)
		{
#define P(x)		(((x)>0)?((x)*(x)*(x)):0.0f)
#define R(x)		( P(x+2) - 4.0f*P(x+1) + 6.0f*P(x) - 4.0f*P(x-1) )*(1.0f/6.0f)
#define F(i,j)		((*this)(subseed,i+x,j+y)*(R((i)-a)*R(b-(j))))
#define FT(i,j,k,l)	((*this)(subseed,i+x,j+y,l)*(R((i)-a)*R(b-(j))*R((k)-c)))
#define Z(i,j)		ret+=F(i,j)
#define ZT(i,j,k,l) ret+=FT(i,j,k,l)
#define X(i,j)		// placeholder... To make box more symmetric
#define XT(i,j,k,l)	// placeholder... To make box more symmetric

		float a(xf-x), b(yf-y);

		// Interpolate
		float ret(F(0,0));
		Z(-1,-1); Z(-1, 0); Z(-1, 1); Z(-1, 2);
		Z( 0,-1); X( 0, 0); Z( 0, 1); Z( 0, 2);
		Z( 1,-1); Z( 1, 0); Z( 1, 1); Z( 1, 2);
		Z( 2,-1); Z( 2, 0); Z( 2, 1); Z( 2, 2);

		return ret;
	}

	case SMOOTH_SPLINE:	// Spline (animated)
		{
			float a(xf-x), b(yf-y), c(tf-t);

			// Interpolate
			float ret(FT(0,0,0,t0));
			ZT(-1,-1,-1,t_1); ZT(-1, 0,-1,t_1); ZT(-1, 1,-1,t_1); ZT(-1, 2,-1,t_1);
			ZT( 0,-1,-1,t_1); ZT( 0, 0,-1,t_1); ZT( 0, 1,-1,t_1); ZT( 0, 2,-1,t_1);
			ZT( 1,-1,-1,t_1); ZT( 1, 0,-1,t_1); ZT( 1, 1,-1,t_1); ZT( 1, 2,-1,t_1);
			ZT( 2,-1,-1,t_1); ZT( 2, 0,-1,t_1); ZT( 2, 1,-1,t_1); ZT( 2, 2,-1,t_1);

			ZT(-1,-1, 0,t0 ); ZT(-1, 0, 0,t0 ); ZT(-1, 1, 0,t0 ); ZT(-1, 2, 0,t0 );
			ZT( 0,-1, 0,t0 ); XT( 0, 0, 0,t0 ); ZT( 0, 1, 0,t0 ); ZT( 0, 2, 0,t0 );
			ZT( 1,-1, 0,t0 ); ZT( 1, 0, 0,t0 ); ZT( 1, 1, 0,t0 ); ZT( 1, 2, 0,t0 );
			ZT( 2,-1, 0,t0 ); ZT( 2, 0, 0,t0 ); ZT( 2, 1, 0,t0 ); ZT( 2, 2, 0,t0 );

			ZT(-1,-1, 1,t1 ); ZT(-1, 0, 1,t1 ); ZT(-1, 1, 1,t1 ); ZT(-1, 2, 1,t1 );
			ZT( 0,-1, 1,t1 ); ZT( 0, 0, 1,t1 ); ZT( 0, 1, 1,t1 ); ZT( 0, 2, 1,t1 );
			ZT( 1,-1, 1,t1 ); ZT( 1, 0, 1,t1 ); ZT( 1, 1, 1,t1 ); ZT( 1, 2, 1,t1 );
			ZT( 2,-1, 1,t1 ); ZT( 2, 0, 1,t1 ); ZT( 2, 1, 1,t1 ); ZT( 2, 2, 1,t1 );

			ZT(-1,-1, 2,t2 ); ZT(-1, 0, 2,t2 ); ZT(-1, 1, 2,t2 ); ZT(-1, 2, 2,t2 );
			ZT( 0,-1, 2,t2 ); ZT( 0, 0, 2,t2 ); ZT( 0, 1, 2,t2 ); ZT( 0, 2, 2,t2 );
			ZT( 1,-1, 2,t2 ); ZT( 1, 0, 2,t2 ); ZT( 1, 1, 2,t2 ); ZT( 1, 2, 2,t2 );
			ZT( 2,-1, 2,t2 ); ZT( 2, 0, 2,t2 ); ZT( 2, 1, 2,t2 ); ZT( 2, 2, 2,t2 );

			return ret;

/*

			float dx=xf-x;
			float dy=yf-y;
			float dt=tf-t;

			float ret=0;
			int i,j,h;
			for(h=-1;h<=2;h++)
				for(i=-1;i<=2;i++)
					for(j=-1;j<=2;j++)
						ret+=(*this)(subseed,i+x,j+y,h+t)*(R(i-dx)*R(j-dy)*R(h-dt));
			return ret;
*/
		}
		break;
#undef X
#undef Z
#undef F
#undef P
#undef R

	case SMOOTH_COSINE:
	if((float)t==tf)
	{
		int x((int)floor(xf));
		int y((int)floor(yf));
		float a=xf-x;
		float b=yf-y;
		a=(1.0f-cos(a*PI))*0.5f;
		b=(1.0f-cos(b*PI))*0.5f;
		float c=1.0-a;
		float d=1.0-b;
		int x2=x+1,y2=y+1;
		return
			(*this)(subseed,x,y,t0)*(c*d)+
			(*this)(subseed,x2,y,t0)*(a*d)+
			(*this)(subseed,x,y2,t0)*(c*b)+
			(*this)(subseed,x2,y2,t0)*(a*b);
	}
	else
	{
		float a=xf-x;
		float b=yf-y;
		float c=tf-t;

		a=(1.0f-cos(a*PI))*0.5f;
		b=(1.0f-cos(b*PI))*0.5f;

		// We don't perform this on the time axis, otherwise we won't
		// get smooth motion
		//c=(1.0f-cos(c*PI))*0.5f;

		float d=1.0-a;
		float e=1.0-b;
		float f=1.0-c;

		int x2=x+1,y2=y+1;

		return
			(*this)(subseed,x,y,t0)*(d*e*f)+
			(*this)(subseed,x2,y,t0)*(a*e*f)+
			(*this)(subseed,x,y2,t0)*(d*b*f)+
			(*this)(subseed,x2,y2,t0)*(a*b*f)+
			(*this)(subseed,x,y,t1)*(d*e*c)+
			(*this)(subseed,x2,y,t1)*(a*e*c)+
			(*this)(subseed,x,y2,t1)*(d*b*c)+
			(*this)(subseed,x2,y2,t1)*(a*b*c);
	}
	case SMOOTH_LINEAR:
	if((float)t==tf)
	{
		int x((int)floor(xf));
		int y((int)floor(yf));
		float a=xf-x;
		float b=yf-y;
		float c=1.0-a;
		float d=1.0-b;
		int x2=x+1,y2=y+1;
		return
			(*this)(subseed,x,y,t0)*(c*d)+
			(*this)(subseed,x2,y,t0)*(a*d)+
			(*this)(subseed,x,y2,t0)*(c*b)+
			(*this)(subseed,x2,y2,t0)*(a*b);
	}
	else
	{

		float a=xf-x;
		float b=yf-y;
		float c=tf-t;

		float d=1.0-a;
		float e=1.0-b;
		float f=1.0-c;

		int x2=x+1,y2=y+1;

		return
			(*this)(subseed,x,y,t0)*(d*e*f)+
			(*this)(subseed,x2,y,t0)*(a*e*f)+
			(*this)(subseed,x,y2,t0)*(d*b*f)+
			(*this)(subseed,x2,y2,t0)*(a*b*f)+
			(*this)(subseed,x,y,t1)*(d*e*c)+
			(*this)(subseed,x2,y,t1)*(a*e*c)+
			(*this)(subseed,x,y2,t1)*(d*b*c)+
			(*this)(subseed,x2,y2,t1)*(a*b*c);
	}
	default:
	case SMOOTH_DEFAULT:
		return (*this)(subseed,x,y,t0);
	}
}
Ejemplo n.º 19
0
/* ****************************************************************************
*
* postUpdateContext -
*
* POST /v1/updateContext
* POST /ngsi10/updateContext
*
* Payload In:  UpdateContextRequest
* Payload Out: UpdateContextResponse
*/
std::string postUpdateContext
(
  ConnectionInfo*            ciP,
  int                        components,
  std::vector<std::string>&  compV,
  ParseData*                 parseDataP,
  Ngsiv2Flavour              ngsiV2Flavour
)
{
  UpdateContextResponse*  upcrsP = &parseDataP->upcrs.res;
  UpdateContextRequest*   upcrP  = &parseDataP->upcr.res;
  std::string             answer;

  bool asJsonObject = (ciP->uriParam[URI_PARAM_ATTRIBUTE_FORMAT] == "object" && ciP->outMimeType == JSON);
  bool forcedUpdate = ciP->uriParamOptions[OPT_FORCEDUPDATE];
  //
  // 01. Check service-path consistency
  //
  // If more than ONE service-path is input, an error is returned as response.
  // If ONE service-path is issued and that service path is "", then the default service-path is used.
  // Note that by construction servicePath cannot have 0 elements
  // After these checks, the service-path is checked to be 'correct'.
  //
  if (ciP->servicePathV.size() > 1)
  {
    upcrsP->errorCode.fill(SccBadRequest, "more than one service path in context update request");
    alarmMgr.badInput(clientIp, "more than one service path for an update request");

    TIMED_RENDER(answer = upcrsP->toJsonV1(asJsonObject));
    upcrP->release();

    return answer;
  }
  else if (ciP->servicePathV[0] == "")
  {
    ciP->servicePathV[0] = SERVICE_PATH_ROOT;
  }

  std::string res = servicePathCheck(ciP->servicePathV[0].c_str());
  if (res != "OK")
  {
    upcrsP->errorCode.fill(SccBadRequest, res);

    TIMED_RENDER(answer = upcrsP->toJsonV1(asJsonObject));

    upcrP->release();
    return answer;
  }


  //
  // 02. Send the request to mongoBackend/mongoUpdateContext
  //
  upcrsP->errorCode.fill(SccOk);
  attributesToNotFound(upcrP);

  HttpStatusCode httpStatusCode;
  TIMED_MONGO(httpStatusCode = mongoUpdateContext(upcrP,
                                                  upcrsP,
                                                  ciP->tenant,
                                                  ciP->servicePathV,
                                                  ciP->uriParam,
                                                  ciP->httpHeaders.xauthToken,
                                                  ciP->httpHeaders.correlator,
                                                  ciP->httpHeaders.ngsiv2AttrsFormat,
                                                  forcedUpdate,
                                                  ciP->apiVersion,
                                                  ngsiV2Flavour));

  if (ciP->httpStatusCode != SccCreated)
  {
    ciP->httpStatusCode = httpStatusCode;
  }

  foundAndNotFoundAttributeSeparation(upcrsP, upcrP, ciP);



  //
  // 03. Normal case - no forwards
  //
  // If there is nothing to forward, just return the result
  //
  bool forwarding = forwardsPending(upcrsP);
  LM_T(LmtForward, ("forwardsPending returned %s", FT(forwarding)));
  if (forwarding == false)
  {
    TIMED_RENDER(answer = upcrsP->toJsonV1(asJsonObject));

    upcrP->release();
    return answer;
  }



  //
  // 04. mongoBackend doesn't give us the values of the attributes.
  //     So, here we have to do a search inside the initial UpdateContextRequest to fill in all the
  //     attribute-values in the output from mongoUpdateContext
  //
  for (unsigned int cerIx = 0; cerIx < upcrsP->contextElementResponseVector.size(); ++cerIx)
  {
    Entity* eP = &upcrsP->contextElementResponseVector[cerIx]->entity;

    for (unsigned int aIx = 0; aIx < eP->attributeVector.size(); ++aIx)
    {
      ContextAttribute* aP = upcrP->attributeLookup(eP, eP->attributeVector[aIx]->name);

      if (aP == NULL)
      {
        LM_E(("Internal Error (attribute '%s' not found)", eP->attributeVector[aIx]->name.c_str()));
      }
      else
      {
        eP->attributeVector[aIx]->stringValue    = aP->stringValue;
        eP->attributeVector[aIx]->numberValue    = aP->numberValue;
        eP->attributeVector[aIx]->boolValue      = aP->boolValue;
        eP->attributeVector[aIx]->valueType      = aP->valueType;
        eP->attributeVector[aIx]->compoundValueP = aP->compoundValueP == NULL ? NULL : aP->compoundValueP->clone();
      }
    }
  }


  //
  // 05. Forwards necessary - sort parts in outgoing requestV
  //     requestV is a vector of UpdateContextRequests and each Context Provider
  //     will have a slot in the vector.
  //     When a ContextElementResponse is found in the output from mongoUpdateContext, a
  //     UpdateContextRequest is to be found/created and inside that UpdateContextRequest
  //     a ContextElement for the Entity of the ContextElementResponse.
  //
  //     Non-found parts go directly to 'response'.
  //
  UpdateContextRequestVector  requestV;
  UpdateContextResponse       response;

  response.errorCode.fill(SccOk);
  for (unsigned int cerIx = 0; cerIx < upcrsP->contextElementResponseVector.size(); ++cerIx)
  {
    ContextElementResponse* cerP  = upcrsP->contextElementResponseVector[cerIx];

    if (cerP->entity.attributeVector.size() == 0)
    {
      //
      // If we find a contextElement without attributes here, then something is wrong
      //
      LM_E(("Orion Bug (empty contextAttributeVector for ContextElementResponse %d)", cerIx));
    }
    else
    {
      for (unsigned int aIx = 0; aIx < cerP->entity.attributeVector.size(); ++aIx)
      {
        ContextAttribute* aP = cerP->entity.attributeVector[aIx];

        //
        // 0. If the attribute is 'not-found' - just add the attribute to the outgoing response
        //
        if (aP->found == false)
        {
          ContextAttribute ca(aP);
          response.notFoundPush(&cerP->entity, &ca, NULL);
          continue;
        }


        //
        // 1. If the attribute is found locally - just add the attribute to the outgoing response
        //
        if (aP->providingApplication.get() == "")
        {
          ContextAttribute ca(aP);
          response.foundPush(&cerP->entity, &ca);
          continue;
        }


        //
        // 2. Lookup UpdateContextRequest in requestV according to providingApplication.
        //    If not found, add one.
        UpdateContextRequest*  reqP = requestV.lookup(aP->providingApplication.get());
        if (reqP == NULL)
        {
          reqP = new UpdateContextRequest(aP->providingApplication.get(), aP->providingApplication.providerFormat, &cerP->entity);
          reqP->updateActionType = ActionTypeUpdate;
          requestV.push_back(reqP);
        }

        //
        // 3. Lookup ContextElement in UpdateContextRequest according to EntityId.
        //    If not found, add one (to the EntityVector of the UpdateContextRequest).
        //
        Entity* eP = reqP->entityVector.lookup(cerP->entity.id, cerP->entity.type);
        if (eP == NULL)
        {
          eP = new Entity();
          eP->fill(cerP->entity.id, cerP->entity.type, cerP->entity.isPattern);
          reqP->entityVector.push_back(eP);
        }


        //
        // 4. Add ContextAttribute to the correct ContextElement in the correct UpdateContextRequest
        //
        eP->attributeVector.push_back(new ContextAttribute(aP));
      }
    }
  }


  //
  // Now we are ready to forward the Updates
  //


  //
  // Calling each of the Context Providers, merging their results into the
  // total response 'response'
  //
  bool forwardOk = true;

  for (unsigned int ix = 0; ix < requestV.size() && ix < cprForwardLimit; ++ix)
  {
    if (requestV[ix]->contextProvider == "")
    {
      LM_E(("Internal Error (empty context provider string)"));
      continue;
    }

    UpdateContextResponse upcrs;
    bool                  b;

    b = updateForward(ciP, requestV[ix], &upcrs);

    if (b == false)
    {
      forwardOk = false;
    }

    //
    // Add the result from the forwarded update to the total response in 'response'
    //
    response.merge(&upcrs);
  }

  //
  // Note this is a slight break in the separation of concerns among the different layers (i.e.
  // serviceRoutine/ logic should work in a "NGSIv1 isolated context"). However, it seems to be
  // a smart way of dealing with partial update situations
  //
  if (ciP->apiVersion == V2)
  {
    LM_T(LmtForward, ("ciP->apiVersion == V2"));
    //
    // Adjust OrionError response in the case of partial updates. This may happen in CPr forwarding
    // scenarios. Note that mongoBackend logic "splits" successfull updates and failing updates in
    // two different CER (maybe using the same entity)
    //
    std::string failing = "";
    unsigned int failures  = 0;

    LM_T(LmtForward, ("Going over a contextElementResponseVector of %d items", response.contextElementResponseVector.size()));
    for (unsigned int ix = 0; ix < response.contextElementResponseVector.size(); ++ix)
    {
      ContextElementResponse* cerP = response.contextElementResponseVector[ix];

      if (cerP->statusCode.code != SccOk)
      {
        failures++;

        std::string failingPerCer = "";
        for (unsigned int jx = 0; jx < cerP->entity.attributeVector.size(); ++jx)
        {
          failingPerCer += cerP->entity.attributeVector[jx]->name;
          if (jx != cerP->entity.attributeVector.size() - 1)
          {
            failingPerCer +=", ";
          }
        }

        failing += cerP->entity.id + "-" + cerP->entity.type + " : [" + failingPerCer + "], ";
      }
    }

    //
    // Note that we modify parseDataP->upcrs.res.oe and not response.oe, as the former is the
    // one used by the calling postBatchUpdate() function at serviceRoutineV2 library
    //
    if ((forwardOk == true) && (failures == 0))
    {
      parseDataP->upcrs.res.oe.fill(SccNone, "");
    }
    else if (failures == response.contextElementResponseVector.size())
    {
      parseDataP->upcrs.res.oe.fill(SccContextElementNotFound, ERROR_DESC_NOT_FOUND_ENTITY, ERROR_NOT_FOUND);
    }
    else if (failures > 0)
    {
      // Removing trailing ", "
      failing = failing.substr(0, failing.size() - 2);

      // If some CER (but not all) fail, then it is a partial update
      parseDataP->upcrs.res.oe.fill(SccContextElementNotFound, "Attributes that were not updated: { " + failing + " }", "PartialUpdate");
    }
    else  // failures == 0
    {
      // No failure, so invalidate any possible OrionError filled by mongoBackend on the mongoUpdateContext step
      parseDataP->upcrs.res.oe.fill(SccNone, "");
    }
  }
  else  // v1
  {
    LM_T(LmtForward, ("ciP->apiVersion != V2"));
    // Note that v2 case doesn't use an actual response (so no need to waste time rendering it).
    // We render in the v1 case only
    TIMED_RENDER(answer = response.toJsonV1(asJsonObject));
  }

  //
  // Cleanup
  //
  upcrP->release();
  requestV.release();
  upcrsP->release();
  upcrsP->fill(&response);
  response.release();

  return answer;
}
Ejemplo n.º 20
0
int tl_image_convert(tl_image* to, tl_image* from)
{
	u32 hleft = from->h;
	u32 w = from->w;
	int fbpp = from->bpp;
	int tbpp = to->bpp;
	u8* tp = to->pixels;
	u8* fp = from->pixels;
	u32 tpitch = tl_image_pitch(to);
	u32 fpitch = tl_image_pitch(from);
	u32 i;
	
	if(to->w != from->w || to->h != from->h)
		return -1;

	assert(fbpp >= 1 && fbpp <= 4);
	assert(tbpp >= 1 && tbpp <= 4);

	{
		u32 id = ((fbpp << 2) + tbpp) - ((1<<2)+1);
		// id is a value in [0, 16)

		#define FT(f,t) ((((f)-1)<<2)+((t)-1))

		if(fbpp == tbpp)
		{
			u32 fline = from->w * from->bpp;
			for(; hleft-- > 0; tp += tpitch, fp += fpitch)
				memcpy(tp, fp, fline);
		}
		else switch (id)
		{
			case FT(1,4):
			{
				for(; hleft-- > 0; tp += tpitch, fp += fpitch)
				for(i = 0; i < w; ++i)
				{
					u8 f = fp[i];
					/*
					tp[i*4  ] = f;
					tp[i*4+1] = f;
					tp[i*4+2] = f;
					tp[i*4+3] = 255;*/
					tp[i*4  ] = 255;
					tp[i*4+1] = 255;
					tp[i*4+2] = 255;
					tp[i*4+3] = f;
				}
				break;
			}
		}

		#undef FT
	}

	return 0;

	// 1 L
	// 2 L A
	// 3 R G B
	// 4 R G B A


	// L       -> L *
	// L       -> L L L
	// L       -> L L L *
	// L A     -> L
	// L A     -> L L L
	// L A     -> L L L A
	// R G B   -> M
	// R G B   -> M *
	// R G B   -> R G B *
	// R G B A -> M
	// R G B A -> M *
	// R G B A -> R G B
}
Ejemplo n.º 21
0
 FT operator()(Triangle_3)const{return FT();}
Ejemplo n.º 22
0
 FT operator()(const Point_3& , const Point_3& ){return FT();}
Ejemplo n.º 23
0
  void AxisymmetricHeatTransfer<Conductivity>::element_time_derivative( bool compute_jacobian,
									AssemblyContext& context,
									CachedValues& /*cache*/ )
  {
#ifdef GRINS_USE_GRVY_TIMERS
    this->_timer->BeginTimer("AxisymmetricHeatTransfer::element_time_derivative");
#endif

    // The number of local degrees of freedom in each variable.
    const unsigned int n_T_dofs = context.get_dof_indices(_T_var).size();
    const unsigned int n_u_dofs = context.get_dof_indices(_u_r_var).size();

    //TODO: check n_T_dofs is same as n_u_dofs, n_v_dofs, n_w_dofs

    // We get some references to cell-specific data that
    // will be used to assemble the linear system.

    // Element Jacobian * quadrature weights for interior integration.
    const std::vector<libMesh::Real> &JxW =
      context.get_element_fe(_T_var)->get_JxW();

    // The temperature shape functions at interior quadrature points.
    const std::vector<std::vector<libMesh::Real> >& T_phi =
      context.get_element_fe(_T_var)->get_phi();

    // The velocity shape functions at interior quadrature points.
    const std::vector<std::vector<libMesh::Real> >& vel_phi =
      context.get_element_fe(_u_r_var)->get_phi();

    // The temperature shape function gradients (in global coords.)
    // at interior quadrature points.
    const std::vector<std::vector<libMesh::RealGradient> >& T_gradphi =
      context.get_element_fe(_T_var)->get_dphi();

    // Physical location of the quadrature points
    const std::vector<libMesh::Point>& u_qpoint =
      context.get_element_fe(_u_r_var)->get_xyz();

    // The subvectors and submatrices we need to fill:
    libMesh::DenseSubVector<libMesh::Number> &FT = context.get_elem_residual(_T_var); // R_{T}

    libMesh::DenseSubMatrix<libMesh::Number> &KTT = context.get_elem_jacobian(_T_var, _T_var); // R_{T},{T}

    libMesh::DenseSubMatrix<libMesh::Number> &KTr = context.get_elem_jacobian(_T_var, _u_r_var); // R_{T},{r}
    libMesh::DenseSubMatrix<libMesh::Number> &KTz = context.get_elem_jacobian(_T_var, _u_z_var); // R_{T},{z}


    // Now we will build the element Jacobian and residual.
    // Constructing the residual requires the solution and its
    // gradient from the previous timestep.  This must be
    // calculated at each quadrature point by summing the
    // solution degree-of-freedom values by the appropriate
    // weight functions.
    unsigned int n_qpoints = context.get_element_qrule().n_points();

    for (unsigned int qp=0; qp != n_qpoints; qp++)
      {
	const libMesh::Number r = u_qpoint[qp](0);
      
	// Compute the solution & its gradient at the old Newton iterate.
	libMesh::Number u_r, u_z;
	u_r = context.interior_value(_u_r_var, qp);
	u_z = context.interior_value(_u_z_var, qp);

	libMesh::Gradient grad_T;
	grad_T = context.interior_gradient(_T_var, qp);

	libMesh::NumberVectorValue U (u_r,u_z);

	libMesh::Number k = this->_k( context, qp );

        // FIXME - once we have T-dependent k, we'll need its
        // derivatives in Jacobians
	// libMesh::Number dk_dT = this->_k.deriv( T );

	// First, an i-loop over the  degrees of freedom.
	for (unsigned int i=0; i != n_T_dofs; i++)
	  {
	    FT(i) += JxW[qp]*r*
	      (-_rho*_Cp*T_phi[i][qp]*(U*grad_T)    // convection term
	       -k*(T_gradphi[i][qp]*grad_T) );  // diffusion term

	    if (compute_jacobian)
	      {
		libmesh_assert (context.get_elem_solution_derivative() == 1.0);

		for (unsigned int j=0; j != n_T_dofs; j++)
		  {
		    // TODO: precompute some terms like:
		    //   _rho*_Cp*T_phi[i][qp]*(vel_phi[j][qp]*T_grad_phi[j][qp])

		    KTT(i,j) += JxW[qp] * context.get_elem_solution_derivative() *r*
		      (-_rho*_Cp*T_phi[i][qp]*(U*T_gradphi[j][qp])  // convection term
		       -k*(T_gradphi[i][qp]*T_gradphi[j][qp])); // diffusion term
		  } // end of the inner dof (j) loop

#if 0
		if( dk_dT != 0.0 )
		{
		  for (unsigned int j=0; j != n_T_dofs; j++)
		    {
		      // TODO: precompute some terms like:
		      KTT(i,j) -= JxW[qp] * context.get_elem_solution_derivative() *r*( dk_dT*T_phi[j][qp]*T_gradphi[i][qp]*grad_T );
		    }
		}
#endif

		// Matrix contributions for the Tu, Tv and Tw couplings (n_T_dofs same as n_u_dofs, n_v_dofs and n_w_dofs)
		for (unsigned int j=0; j != n_u_dofs; j++)
		  {
		    KTr(i,j) += JxW[qp] * context.get_elem_solution_derivative() *r*(-_rho*_Cp*T_phi[i][qp]*(vel_phi[j][qp]*grad_T(0)));
		    KTz(i,j) += JxW[qp] * context.get_elem_solution_derivative() *r*(-_rho*_Cp*T_phi[i][qp]*(vel_phi[j][qp]*grad_T(1)));
		  } // end of the inner dof (j) loop

	      } // end - if (compute_jacobian && context.get_elem_solution_derivative())

	  } // end of the outer dof (i) loop
      } // end of the quadrature point (qp) loop

#ifdef GRINS_USE_GRVY_TIMERS
    this->_timer->EndTimer("AxisymmetricHeatTransfer::element_time_derivative");
#endif

    return;
  }
Ejemplo n.º 24
0
 FT operator[](int)const{return FT();}
Ejemplo n.º 25
0
 FT operator()(Segment_3)const{return FT();}
Ejemplo n.º 26
0
void create(void) {

  int N=simu.no_of_particles();
  std::vector<Point> points;
  //  points.reserve(N);

  if(simu.create_points()) {
    if(simu.at_random()) {
      points.reserve(N);

      CGAL::Random_points_in_square_2<Point,Creator> g(LL/2.0-0.0001);
      CGAL::cpp11::copy_n( g, N, std::back_inserter(points));


      cout << N << "  particles placed at random" << endl;
    } else {
      // if((plotting)&&(Nin%2==0)&&(spike)) {
      // 	cout << "Please enter an odd number of particles" << endl;
      // 	std::abort();
      // }

      int Nb=sqrt(N + 1e-12);

      N=Nb*Nb;

      simu.set_no_of_particles(N);

      points.reserve(N);
      cout << N << " particles placed on square lattice" << endl;

      FT spacing=LL/FT(Nb+0);
      FT side=LL-1*spacing;

      points_on_square_grid_2(side/2.0, N, std::back_inserter(points),Creator());;

      //      for(int i = 0 ; i < Nb ; ++i )
	
      
      if(simu.perturb()) {
	CGAL::perturb_points_2(
			       points.begin(), points.end(),
			       simu.pert_rel()* spacing );//,Creator());
	cout << "each particle perturbed about " << simu.pert_rel()* spacing  << endl;
      }

    }

    cout << "Inserting" << endl;

    Tp.insert(points.begin(), points.end());

    points.clear();

    // int Nb = sqrt(N + 1e-12);
    // int nm = Nb* simu.mesh_factor() + 1 ;
    // int Nm = nm * nm;

    int Nm=simu.no_of_nodes();

    int nm=sqrt(Nm + 1e-12);

    Nm= nm * nm;

    simu.set_no_of_nodes(Nm);

    points.reserve(Nm);
    cout << Nm << " mesh on square lattice" << endl;

    FT spacing=LL/FT( nm +0);
    FT side=LL-1*spacing;

    points_on_square_grid_2(side/2.0, Nm , std::back_inserter(points),Creator());;

    // // TODO: perfectly regular square grids are not too good, in fact
    // CGAL::perturb_points_2(
    // 			   points.begin(), points.end(),
    // 			   0.001* spacing );

    Tm.insert(points.begin(), points.end());

  } else {

    int N=simu.no_of_particles();

    char part_file[]="particles.dat";

    cout << "reading from file : " << part_file << endl;

    std::ifstream main_data;
    main_data.open(part_file );

    for(int i=0;i<N;i++) {
      FT x,y;
      main_data >> x;
      main_data >> y;

      //      cout << x << "  " << y << endl;

      Vertex_handle vh=Tp.insert(Point(x,y));

#include"readin.h"


    }
  
    cout << "particles' data read" << endl;

    main_data.close();

    char mesh_file[]="mesh.dat";

    cout << "reading from file : " << mesh_file << endl;

    main_data.open(mesh_file );

    int Nm=simu.no_of_nodes();

    for(int i=0;i<Nm;i++) {
      FT x,y;
      main_data >> x;
      main_data >> y;

      //      cout << x << "  " << y << endl;
      
      Vertex_handle vh=Tm.insert(Point(x,y));

#include"readin.h"


    }
  
    cout << "mesh data read" << endl;

    main_data.close();

  }

  // straight from the manual.-

  Triangulation::Covering_sheets cs = Tp.number_of_sheets();

  cout << "Original covering (particles): " << cs[0] << ' ' << cs[1] << endl;

//  return ;
  
  Tp.convert_to_1_sheeted_covering();

  cs = Tp.number_of_sheets();

  cout << "Current covering (particles): " << cs[0] << ' ' << cs[1] << endl;


  return ;

  if ( Tp.is_triangulation_in_1_sheet() ) // = true
    {
      bool is_extensible = Tp.is_extensible_triangulation_in_1_sheet_h1()
	|| Tp.is_extensible_triangulation_in_1_sheet_h2(); // = false
      Tp.convert_to_1_sheeted_covering();
      cs = Tp.number_of_sheets();
      cout << "Current covering: " << cs[0] << ' ' << cs[1] << endl;
      if ( is_extensible ) // = false
	cout << "It is safe to change the triangulation here." << endl;
      else {
	cout << "It is NOT safe to change the triangulation here!" << endl;
	abort();
      }
      //      T.convert_to_9_sheeted_covering();
      //      cs = T.number_of_sheets();
      //      cout << "Current covering: " << cs[0] << ' ' << cs[1] << endl;
    } else {
	cout << "Triangulation not on one sheet!" << endl;
	abort();    
  }


  //  cout << "It is (again) safe to modify the triangulation." << endl;


  return ;

}
Ejemplo n.º 27
0
  void HeatTransfer::element_time_derivative( bool compute_jacobian,
					      libMesh::FEMContext& context,
					      CachedValues& /*cache*/ )
  {
#ifdef GRINS_USE_GRVY_TIMERS
    this->_timer->BeginTimer("HeatTransfer::element_time_derivative");
#endif

    // The number of local degrees of freedom in each variable.
    const unsigned int n_T_dofs = context.dof_indices_var[_T_var].size();
    const unsigned int n_u_dofs = context.dof_indices_var[_u_var].size();

    //TODO: check n_T_dofs is same as n_u_dofs, n_v_dofs, n_w_dofs

    // We get some references to cell-specific data that
    // will be used to assemble the linear system.

    // Element Jacobian * quadrature weights for interior integration.
    const std::vector<libMesh::Real> &JxW =
      context.element_fe_var[_T_var]->get_JxW();

    // The temperature shape functions at interior quadrature points.
    const std::vector<std::vector<libMesh::Real> >& T_phi =
      context.element_fe_var[_T_var]->get_phi();

    // The velocity shape functions at interior quadrature points.
    const std::vector<std::vector<libMesh::Real> >& vel_phi =
      context.element_fe_var[_u_var]->get_phi();

    // The temperature shape function gradients (in global coords.)
    // at interior quadrature points.
    const std::vector<std::vector<libMesh::RealGradient> >& T_gradphi =
      context.element_fe_var[_T_var]->get_dphi();

    const std::vector<libMesh::Point>& u_qpoint = 
      context.element_fe_var[this->_u_var]->get_xyz();

    // We do this in the incompressible Navier-Stokes class and need to do it here too
    // since _w_var won't have been defined in the global map.
    if (_dim != 3)
      _w_var = _u_var; // for convenience

    libMesh::DenseSubMatrix<libMesh::Number> &KTT = *context.elem_subjacobians[_T_var][_T_var]; // R_{T},{T}

    libMesh::DenseSubMatrix<libMesh::Number> &KTu = *context.elem_subjacobians[_T_var][_u_var]; // R_{T},{u}
    libMesh::DenseSubMatrix<libMesh::Number> &KTv = *context.elem_subjacobians[_T_var][_v_var]; // R_{T},{v}
    libMesh::DenseSubMatrix<libMesh::Number> &KTw = *context.elem_subjacobians[_T_var][_w_var]; // R_{T},{w}

    libMesh::DenseSubVector<libMesh::Number> &FT = *context.elem_subresiduals[_T_var]; // R_{T}

    // Now we will build the element Jacobian and residual.
    // Constructing the residual requires the solution and its
    // gradient from the previous timestep.  This must be
    // calculated at each quadrature point by summing the
    // solution degree-of-freedom values by the appropriate
    // weight functions.
    unsigned int n_qpoints = context.element_qrule->n_points();

    for (unsigned int qp=0; qp != n_qpoints; qp++)
      {
	// Compute the solution & its gradient at the old Newton iterate.
	libMesh::Number u, v, w;
	u = context.interior_value(_u_var, qp);
	v = context.interior_value(_v_var, qp);
	if (_dim == 3)
	  w = context.interior_value(_w_var, qp);

	libMesh::Gradient grad_T;
	grad_T = context.interior_gradient(_T_var, qp);

	libMesh::NumberVectorValue U (u,v);
	if (_dim == 3)
	  U(2) = w;

        const libMesh::Number r = u_qpoint[qp](0);

        libMesh::Real jac = JxW[qp];

        if( _is_axisymmetric )
          {
            jac *= r;
          }

	// First, an i-loop over the  degrees of freedom.
	for (unsigned int i=0; i != n_T_dofs; i++)
	  {
	    FT(i) += jac *
	      (-_rho*_Cp*T_phi[i][qp]*(U*grad_T)    // convection term
	       -_k*(T_gradphi[i][qp]*grad_T) );  // diffusion term

	    if (compute_jacobian)
	      {
		for (unsigned int j=0; j != n_T_dofs; j++)
		  {
		    // TODO: precompute some terms like:
		    //   _rho*_Cp*T_phi[i][qp]*(vel_phi[j][qp]*T_grad_phi[j][qp])

		    KTT(i,j) += jac *
		      (-_rho*_Cp*T_phi[i][qp]*(U*T_gradphi[j][qp])  // convection term
		       -_k*(T_gradphi[i][qp]*T_gradphi[j][qp])); // diffusion term
		  } // end of the inner dof (j) loop

		// Matrix contributions for the Tu, Tv and Tw couplings (n_T_dofs same as n_u_dofs, n_v_dofs and n_w_dofs)
		for (unsigned int j=0; j != n_u_dofs; j++)
		  {
		    KTu(i,j) += jac*(-_rho*_Cp*T_phi[i][qp]*(vel_phi[j][qp]*grad_T(0)));
		    KTv(i,j) += jac*(-_rho*_Cp*T_phi[i][qp]*(vel_phi[j][qp]*grad_T(1)));
		    if (_dim == 3)
		      KTw(i,j) += jac*(-_rho*_Cp*T_phi[i][qp]*(vel_phi[j][qp]*grad_T(2)));
		  } // end of the inner dof (j) loop

	      } // end - if (compute_jacobian && context.elem_solution_derivative)

	  } // end of the outer dof (i) loop
      } // end of the quadrature point (qp) loop

#ifdef GRINS_USE_GRVY_TIMERS
    this->_timer->EndTimer("HeatTransfer::element_time_derivative");
#endif

    return;
  }
Ejemplo n.º 28
0
 FT operator()(Point_3,Point_3,Point_3)const{return FT();}
Ejemplo n.º 29
0
//============================================================
void im_complex::FastFT()
{
   // Calculate Fast 1D FT
   int ydim = Re.Ydim;
   int xdim = Re.Xdim;
   int half_x = xdim / 2;
   if ((ydim == 1) && (xdim > 1) && (xdim % 2 == 0))
   {
      // Make even and odd images
      im_complex even(half_x);
      im_complex odd(half_x);
      for (int x = 0; x < half_x; x++)
      {
	 even.Re.Data1D[x] = Re.Data1D[x + x];
	 even.Im.Data1D[x] = Im.Data1D[x + x];
	 odd.Re.Data1D[x] = Re.Data1D[x + x + 1];
	 odd.Im.Data1D[x] = Im.Data1D[x + x + 1];
      }

      // Calculate even and odd FTs
      even.FastFT();
      odd.FastFT();

      // Combine even and odd FTs
      for (int x = 0; x < half_x; x++)
      {
	 double angle = (2 * M_PI * x) / xdim;
	 double cos_angle = cos(angle);
	 double sin_angle = sin(angle);
	 double odd_re = odd.Re.Data1D[x] * cos_angle
	    - odd.Im.Data1D[x] * sin_angle;
	 double odd_im = odd.Im.Data1D[x] * cos_angle
	    + odd.Re.Data1D[x] * sin_angle;
	 Re.Data1D[x] = (even.Re.Data1D[x] + odd_re) / 2;
	 Im.Data1D[x] = (even.Im.Data1D[x] + odd_im) / 2;
	 Re.Data1D[x + half_x] = (even.Re.Data1D[x] - odd_re) / 2;
	 Im.Data1D[x + half_x] = (even.Im.Data1D[x] - odd_im) / 2;
      }
   }

   // Calculate Slow 1D FT
   else if ((ydim == 1) && (xdim > 1) && (xdim % 2 == 1))
   {
      FT();
   }

   // Calculate Fast 2D FT
   else if ((ydim > 1) && (xdim > 1))
   {
      // Perform 1D FT on each row
      im_complex row(xdim);
      for (int y = 0; y < ydim; y++)
      {
	 for (int x = 0; x < xdim; x++)
	 {
	    row.Re.Data1D[x] = Re.Data2D[y][x];
	    row.Im.Data1D[x] = Im.Data2D[y][x];
	 }
	 row.FastFT();
	 for (int x = 0; x < xdim; x++)
	 {
	    Re.Data2D[y][x] = row.Re.Data1D[x];
	    Im.Data2D[y][x] = row.Im.Data1D[x];
	 }
      }

      // Perform 1D FT on each column
      im_complex column(ydim);
      for (int x = 0; x < xdim; x++)
      {
	 for (int y = 0; y < ydim; y++)
	 {
	    column.Re.Data1D[y] = Re.Data2D[y][x];
	    column.Im.Data1D[y] = Im.Data2D[y][x];
	 }
	 column.FastFT();
	 for (int y = 0; y < ydim; y++)
	 {
	    Re.Data2D[y][x] = column.Re.Data1D[y];
	    Im.Data2D[y][x] = column.Im.Data1D[y];
	 }
      }
   }
}
Ejemplo n.º 30
0
 FT operator()(const Sphere_3&){return FT();}