Beispiel #1
0
int main()
{
    MarchingCubeGridf phi(1,1,1);
    std::ifstream phifile("cube.phi");
    phi.read(phifile);
    Meshf mesh;
    phi.populateMesh(mesh,0);
    std::cout << mesh.vertices.size() << std::endl;
    std::cout << mesh.edges.size() << std::endl;
    std::cout << mesh.faces.size() << std::endl;
    std::ofstream out("output.obj");
    MeshIOUtils::OBJParser<NumericalTraitsXf> parser(&mesh);
    parser.write(out);



}
//**********************************************************************
PHX_EVALUATE_FIELDS(FEInterpolation,cell_data)
{ 

  std::vector<Element_Linear2D>::iterator cell_it = cell_data.begin;

  // Loop over number of cells
  for (std::size_t cell = 0; cell < cell_data.num_cells; ++cell) {
    
    const shards::Array<double,shards::NaturalOrder,QuadPoint,Node>& phi = 
      cell_it->basisFunctions();

    const shards::Array<double,shards::NaturalOrder,QuadPoint,Node,Dim>& 
      grad_phi = cell_it->basisFunctionGradientsRealSpace();

    // Loop over quad points of cell
    for (int qp = 0; qp < num_qp; ++qp) {
      
      val_qp(cell,qp) = 0.0;

      for (int dim = 0; dim < num_dim; ++dim)
	val_grad_qp(cell,qp,dim) = 0.0;

      // Sum nodal contributions to qp
      for (int node = 0; node < num_nodes; ++node) {

	val_qp(cell,qp) += phi(qp,node) * val_node(cell,node);
	
	for (int dim = 0; dim < num_dim; ++dim)
	  val_grad_qp(cell,qp,dim) += 
	    grad_phi(qp,node,dim) * val_node(cell,node);
	
      }
    }
    
    ++cell_it;
 
  }
    
//   std::cout << "FEINterpolation: val_node" << std::endl;
//   val_node.print(std::cout,true);
//   std::cout << "FEINterpolation: val_qp" << std::endl;
//   val_qp.print(std::cout,true);
//   std::cout << "FEINterpolation: val_grad_qp" << std::endl;
//   val_grad_qp.print(std::cout,true);

}
Foam::tmp<Foam::volScalarField>
Foam::diameterModels::IATEsources::randomCoalescence::R() const
{
    tmp<volScalarField> tR
    (
        new volScalarField
        (
            IOobject
            (
                "R",
                iate_.phase().time().timeName(),
                iate_.phase().mesh()
            ),
            iate_.phase().mesh(),
            dimensionedScalar("R", dimless/dimTime, 0)
        )
    );

    volScalarField R = tR();

    scalar Crc = Crc_.value();
    scalar C = C_.value();
    scalar alphaMax = alphaMax_.value();
    volScalarField Ut(this->Ut());
    const volScalarField& alpha = phase();
    const volScalarField& kappai = iate_.kappai();
    scalar cbrtAlphaMax = cbrt(alphaMax);

    forAll(R, celli)
    {
        if (alpha[celli] < alphaMax - SMALL)
        {
            scalar cbrtAlphaMaxMAlpha = cbrtAlphaMax - cbrt(alpha[celli]);

            R[celli] =
                (-12)*phi()*kappai[celli]*alpha[celli]
               *Crc
               *Ut[celli]
               *(1 - exp(-C*cbrt(alpha[celli]*alphaMax)/cbrtAlphaMaxMAlpha))
               /(cbrtAlphaMax*cbrtAlphaMaxMAlpha);
        }
    }

    return tR;
}
Beispiel #4
0
FnMap minimizeLength(const FnWord &u, const Basis &basis)
{

  /* Returns an automorphism phi such that phi(u) has minimal
     length. */

  int r = basis.getRank();
  FnMap phi(r);

  if (u == Id) return phi;
  if (u.length() == 1) return phi;

  int old_norm,new_norm;
  FnWord u_min(u),tmp;
  FnMap whAuto(r);

  QList<WhiteheadData> whAutos = whiteheadAutos(basis);
  QListIterator<WhiteheadData> move(whAutos);

  bool reduced_norm = true;

  while (reduced_norm) {

    old_norm = u_min.length();
    new_norm = old_norm;
    move.toFront();

    while (old_norm <= new_norm && move.hasNext()) {
      whAuto = whitehead(move.next(),basis);
      tmp = whAuto(u_min);
      new_norm = tmp.length();
    }
    if (new_norm < old_norm) {
      u_min = tmp;
      phi = whAuto*phi;
    } else
      reduced_norm = false;
  } // end while (reduced_norm)
 
  // now u_min = phi(u)

  return phi;

} 
Beispiel #5
0
void Foam::Leonov::correct()
{
    // Velocity gradient tensor
    volTensorField L = fvc::grad(U());

    // Convected derivate term
    volTensorField C = sigma_ & L;

    // Twice the rate of deformation tensor
    volSymmTensorField twoD = twoSymm(L);

    // Two phase transport properties treatment
    volScalarField alpha1f = min(max(alpha(), scalar(0)), scalar(1));

    volScalarField lambda =  alpha1f*lambda1_ + (scalar(1) - alpha1f)*lambda2_;

    volScalarField etaP =  alpha1f*etaP1_ + (scalar(1) - alpha1f)*etaP2_;

     // Stress transport equation
    fvSymmTensorMatrix sigmaEqn
    (
        fvm::ddt(sigma_)
      + fvm::div(phi(), sigma_)
     ==
        twoSymm(C)
      - 1/etaP/2*(symm(sigma_ & sigma_) - Foam::pow((etaP/lambda), 2)*I_)
      + fvm::Sp
        (
            1/etaP/6*
            (
                tr(sigma_)
              - Foam::pow(etaP/lambda,2) * tr(inv(sigma_))
            ),
            sigma_
        )
    );


    sigmaEqn.relax();
    sigmaEqn.solve();

    // Viscoelastic stress
    tau_ = sigma_ - etaP/lambda*I_;
}
Beispiel #6
0
void getError(LevelData<double, 1> & a_error,
              double               & a_maxError,
              const double         & a_dx)
{

  BoxLayout layout = a_error.getBoxLayout();

  LevelData<double, 1> phi(layout, s_nghost);
  LevelData<double, 1> lphcalc(layout, 0);
  LevelData<double, 1> lphexac(layout, 0);

  //  cout << "initializing phi to sum_dir(sin 2*pi*xdir)" << endl;
  initialize(phi,lphexac, a_dx);

  //set ghost cells of phi
  phi.exchange();
  //  dumpLevelRDA(&phi);
  Stencil<double> laplace;
  setStencil(laplace, a_dx);

  //apply stencil operator independently on each box
  a_maxError = 0;
  
  for(BLIterator blit(layout); blit != blit.end(); ++blit)
    {
      RectMDArray<double>& phiex =     phi[*blit];
      RectMDArray<double>& lphca = lphcalc[*blit];
      RectMDArray<double>& lphex = lphexac[*blit];
      RectMDArray<double>& error = a_error[*blit];

      //apply is set as an increment so need to set this to zero initially
      lphca.setVal(0.);

      Box bxdst=layout[*blit];
      Stencil<double>::apply(laplace, phiex, lphca, bxdst);
        
      //error = lphicalc -lphiexac
      lphca.copyTo(error);
      //here err holds lphi calc
      double maxbox = forall_max(error, lphex, &errorF, bxdst);

      a_maxError = max(maxbox, a_maxError);
    }
}
///* Computation of Critical Rate in the Jamishidian decomposition, with the newton method to find zero of a function
static double Critical_Rate(ZCMarketData* ZCMarket, double r_initial, double periodicity, double option_maturity, double contract_maturity, double SwaptionFixedRate, double a, double sigma)
{
  double previous,current;
  int nbr_iterations;

  const double precision = 0.000001;

  current = r_initial;
  nbr_iterations = 0;

  do
    {
      nbr_iterations++;
      previous =current;
      current=current-phi(ZCMarket, current, periodicity, option_maturity, contract_maturity, SwaptionFixedRate, a, sigma);
    } while((fabs(previous-current) > precision) && (nbr_iterations <= 50));

  return current;
}
Beispiel #8
0
int main()
{
    long long i,j;
    boolean[0]=1;
    boolean[1]=1;
    for(i=2;i*i<55000;i++)
    {
        if(!boolean[i])
        {
            for(j=i*i;j<55000;j+=i)
            {
                boolean[j]=1;
            }
        }
    }

    int index=0;
    for(i=2;i<55000;i++)
    {
        if(!boolean[i])
        {
            primes[index++]=i;
        }
    }
    coprimes[0]=1;
    long long global=1;
    for(i=1;i<50000;i++)
    {
        coprimes[i]=2*phi(i+1);
    }

    long long input;
    while(scanf("%lld",&input)==1 && input)
    {
        long long output=0;
        for(i=input-1;i>=0;i--)
        {
            output+=coprimes[i];
        }
        printf("%lld\n",output);
    }
    return 0;
}
Beispiel #9
0
    Euler(const Dcm<Type> & dcm) : Vector<Type, 3>()
    {
        Type phi_val = Type(atan2(dcm(2,1), dcm(2,2)));
        Type theta_val = Type(asin(-dcm(2,0)));
        Type psi_val = Type(atan2(dcm(1,0), dcm(0,0)));
        Type pi = Type(M_PI);

        if (fabs(theta_val - pi/2) < 1.0e-3) {
            phi_val = Type(0.0);
            psi_val = Type(atan2(dcm(1,2), dcm(0,2)));
        } else if (Type(fabs(theta_val + pi/2)) < Type(1.0e-3)) {
            phi_val = Type(0.0);
            psi_val = Type(atan2(-dcm(1,2), -dcm(0,2)));
        }

        phi() = phi_val;
        theta() = theta_val;
        psi() = psi_val;
    }
void NSForchheimerTerm<EvalT, Traits>::
evaluateFields(typename Traits::EvalData workset)
{
  for (std::size_t cell=0; cell < workset.numCells; ++cell) {
    for (std::size_t qp=0; qp < numQPs; ++qp) {     
      normV(cell,qp) = 0.0; 
      for (std::size_t i=0; i < numDims; ++i) {
          normV(cell,qp) += V(cell,qp,i)*V(cell,qp,i); 
      } 
      if (normV(cell,qp) > 0)
        normV(cell,qp) = std::sqrt(normV(cell,qp));
      else
        normV(cell,qp) = 0.0;
      for (std::size_t i=0; i < numDims; ++i) {
          ForchTerm(cell,qp,i) = phi(cell,qp)*rho(cell,qp)*F(cell,qp)*normV(cell,qp)*V(cell,qp,i)/std::sqrt(K(cell,qp));
      } 
    }
  }
}
  void mk_array_instantiation::instantiate_rule(const rule& r, rule_set & dest)
  {
    //Reset everything
    selects.reset();
    eq_classes.reset();
    cnt = src_manager->get_counter().get_max_rule_var(r)+1;
    done_selects.reset();
    ownership.reset();

    expr_ref_vector phi(m);
    expr_ref_vector preds(m);
    expr_ref new_head = create_head(to_app(r.get_head()));
    unsigned nb_predicates = r.get_uninterpreted_tail_size();
    unsigned tail_size = r.get_tail_size();
    for(unsigned i=0;i<nb_predicates;i++)
    {
      preds.push_back(r.get_tail(i));
    }
    for(unsigned i=nb_predicates;i<tail_size;i++)
    {
      phi.push_back(r.get_tail(i));
    }

    //Retrieve selects
    for(unsigned i=0;i<phi.size();i++)
      retrieve_selects(phi[i].get());

    //Rewrite the predicates
    expr_ref_vector new_tail(m);
    for(unsigned i=0;i<preds.size();i++)
    {
      new_tail.append(instantiate_pred(to_app(preds[i].get())));
    }
    new_tail.append(phi);
    for(obj_map<expr, var*>::iterator it = done_selects.begin(); it!=done_selects.end(); ++it)
    {
      expr_ref tmp(m);
      tmp = &it->get_key();
      new_tail.push_back(m.mk_eq(it->get_value(), tmp));
    }
    proof_ref pr(m);
    src_manager->mk_rule(m.mk_implies(m.mk_and(new_tail.size(), new_tail.c_ptr()), new_head), pr, dest, r.name());
  }
Beispiel #12
0
void Feta_PTT::correct()
{
    // Velocity gradient tensor
    volTensorField L = fvc::grad( U() );

    // Convected derivate term
    volTensorField C = tau_ & L;

    // Twice the rate of deformation tensor
    volSymmTensorField twoD = twoSymm( L );

    // Two phase transport properties treatment
    alpha1f_ = min(max(alpha(), scalar(0)), scalar(1));

    // etaP effective
    etaPEff_ =  (etaP1_/( Foam::pow(scalar(1) + A1_*Foam::pow(0.5*( Foam::sqr(tr(tau_)) - tr(tau_ & tau_) ) * Foam::sqr(lambda1_) / Foam::sqr(etaP1_), a1_), b1_) ) )*alpha1f_ + (etaP2_/( Foam::pow(scalar(1) + A2_*Foam::pow(0.5*( Foam::sqr(tr(tau_)) - tr(tau_ & tau_) ) * Foam::sqr(lambda2_) / Foam::sqr(etaP2_), a2_), b2_) ) )*(scalar(1) - alpha1f_);

    // lambda effective
    lambdaEff_ =  (lambda1_ / (scalar(1)  + epsilon1_*lambda1_*tr(tau_) / etaP1_) )*alpha1f_ + (lambda2_ / (scalar(1)  + epsilon2_*lambda2_*tr(tau_) / etaP2_) )*(scalar(1) - alpha1f_);

    volScalarField epsilon =  alpha1f_*epsilon1_ + (scalar(1) - alpha1f_)*epsilon2_;

    volScalarField zeta =  alpha1f_*zeta1_ + (scalar(1) - alpha1f_)*zeta2_;

     // Stress transport equation
    tmp<fvSymmTensorMatrix> tauEqn
    (
          fvm::ddt(lambdaEff_, tau_)
        + lambdaEff_ * fvm::div(phi(), tau_)
        ==
          etaPEff_ * twoD
        + lambdaEff_ * twoSymm( C )
        - zeta * lambdaEff_ /2* symm( (tau_ & twoD) + (twoD & tau_) )
	  //add "twoSymm"(...), by Martin R. Du, [email protected]
	  //replace "*twoSymm" with "*symm", Martin R. Du, 2015/08/08
        - fvm::Sp( epsilon * lambdaEff_ / etaPEff_ * tr(tau_) + 1, tau_ )
    );

    tauEqn().relax();
    solve(tauEqn);

}
Beispiel #13
0
/***********************************************************************//**
 * @brief Sum effective area multiplied by livetime over zenith angles
 *
 * @param[in] dir True sky direction.
 * @param[in] energy True photon energy.
 * @param[in] offset Offset from true direction (deg).
 * @param[in] psf Point spread function.
 * @param[in] aeff Effective area.
 *
 * Computes
 * \f[\sum_{\cos \theta} T_{\rm live}(\cos \theta) 
 *    PSF(\log E, \delta, \cos \theta) A_{\rm eff}(\cos \theta, \phi)\f]
 * where
 * \f$T_{\rm live}(\cos \theta)\f$ is the livetime as a function of the
 * cosine of the zenith angle, and
 * \f$PSF(\log E, \delta, \cos \theta)\f$ is the point spread function that
 * depends on
 * the log10 of the energy (in MeV),
 * the offset angle from the true direction (in degrees), and
 * the cosine of the zenith angle, and
 * \f$A_{\rm eff}(\cos \theta, \phi)\f$ is the effective area that depends
 * on the cosine of the zenith angle and (optionally) of the azimuth angle.
 ***************************************************************************/
double GLATLtCubeMap::operator()(const GSkyDir& dir, const GEnergy& energy,
                                 const double& offset, const GLATPsf& psf,
                                 const GLATAeff& aeff) const
{
    // Get map index
    int pixel = m_map.dir2pix(dir);

    // Initialise sum
    double sum = 0.0;

    // Circumvent const correctness
    GLATPsf*  fpsf  = const_cast<GLATPsf*>(&psf);
    GLATAeff* faeff = const_cast<GLATAeff*>(&aeff);

    // Get log10 of energy
    double logE = energy.log10MeV();

    // If livetime cube and response have phi dependence then sum over
    // zenith and azimuth. Note that the map index starts with m_num_ctheta
    // as the first m_num_ctheta maps correspond to an evaluation without
    // any phi-dependence.
    if (has_phi() && aeff.has_phi()) {
        for (int iphi = 0, i = m_num_ctheta; iphi < m_num_phi; ++iphi) {
            double p = phi(iphi);
            for (int itheta = 0; itheta < m_num_ctheta; ++itheta, ++i) {
                sum += m_map(pixel, i) * (*faeff)(logE, costheta(i), p) *
                       (*fpsf)(offset, logE, costheta(i));
            }
        }
    }

    // ... otherwise sum only over zenith angle
    else {
        for (int i = 0; i < m_num_ctheta; ++i) {
            sum += m_map(pixel, i) * (*faeff)(logE, costheta(i)) *
                   (*fpsf)(offset, logE, costheta(i));
        }
    }

    // Return sum
    return sum;
}
Beispiel #14
0
void FENE_P::correct()
{
    // Velocity gradient tensor
    volTensorField L = fvc::grad(U());

    // Convected derivate term
    volTensorField C = tau_ & L;

    // Twice the rate of deformation tensor
    volSymmTensorField twoD = twoSymm(L);

    // Two phase transport properties treatment
    volScalarField alpha1f = 
		min(max(alpha(),scalar(0)),scalar(1));

    volScalarField lambda =  
		alpha1f*lambda1_ + (scalar(1) - alpha1f)*lambda2_;

    volScalarField etaP =  
		alpha1f*etaP1_ + (scalar(1) - alpha1f)*etaP2_;

    volScalarField Lquad =  
		alpha1f*Lquad1_ + (scalar(1) - alpha1f)*Lquad2_;

     // Stress transport equation
    tmp<fvSymmTensorMatrix> tauEqn
    (
		fvm::ddt(lambda, tau_)
	  + lambda * fvm::div(phi(), tau_)
	 ==
		( 1 / (1 - 3/Lquad) ) * etaP * twoD
	  + lambda * twoSymm( C )
	  - fvm::Sp
		( 
			1  + (3/(1 - 3/Lquad) + lambda*tr(tau_)/etaP )/Lquad, 
			tau_ 
		)
    );

    tauEqn().relax();
    solve(tauEqn);
}
void ContinuumMechanicsNeumannBcsAssembler<DIM>::AssembleOnBoundaryElement(BoundaryElement<DIM-1,DIM>& rBoundaryElement,
                                                                           c_vector<double,STENCIL_SIZE>& rBelem,
                                                                           unsigned boundaryConditionIndex)
{
    rBelem.clear();

    c_vector<double, DIM> weighted_direction;
    double jacobian_determinant;
    mpMesh->GetWeightedDirectionForBoundaryElement(rBoundaryElement.GetIndex(), weighted_direction, jacobian_determinant);

    c_vector<double,NUM_NODES_PER_ELEMENT> phi;

    for (unsigned quad_index=0; quad_index<mpQuadRule->GetNumQuadPoints(); quad_index++)
    {
        double wJ = jacobian_determinant * mpQuadRule->GetWeight(quad_index);
        const ChastePoint<DIM-1>& quad_point = mpQuadRule->rGetQuadPoint(quad_index);
        QuadraticBasisFunction<DIM-1>::ComputeBasisFunctions(quad_point, phi);

        c_vector<double,DIM> traction = zero_vector<double>(DIM);
        switch (mpProblemDefinition->GetTractionBoundaryConditionType())
        {
            case ELEMENTWISE_TRACTION:
            {
                traction = mpProblemDefinition->rGetElementwiseTractions()[boundaryConditionIndex];
                break;
            }
            default:
                // Functional traction not implemented yet..
                NEVER_REACHED;
        }

        for (unsigned index=0; index<NUM_NODES_PER_ELEMENT*DIM; index++)
        {
            unsigned spatial_dim = index%DIM;
            unsigned node_index = (index-spatial_dim)/DIM;

            assert(node_index < NUM_NODES_PER_ELEMENT);

            rBelem(index) += traction(spatial_dim) * phi(node_index) * wJ;
        }
    }
}
/******************************************************************
* It computes a sum of a series of values, as needed by formula   *
* 11.25 of "Inside Solid State Drives" book. It helps performing  *
* Horizontal step of Log-Domain Belief Propagation algorithm.     *
******************************************************************/
double log_bp_error_corrector::phi(double** R, int i, int j)
{
	double result;

	result = 0;

	std::list<edge> edges = chk_nodes[j].get_edges();
	std::list<edge>::iterator it;

	for(it = edges.begin(); it != edges.end(); it++){

		int l = (*it).get_dest().get_idx();

		if(l != i){
			result += phi(abs(R[l][j]));
		}
	}

	return result;
}
Beispiel #17
0
void LevelSetViewerWidget::openFile(const QString & filename)
{
    m_ready = false;
    qWarning() << "Loading file: "<< filename;
    if(m_obj){delete m_obj;}
    std::ifstream in(filename.toStdString().c_str());
    if(m_grid){delete m_grid;}
    m_grid = new Gridf();
    m_grid->read(in);
    std::cout << m_grid->NI() << " " << m_grid->NJ() << " " << m_grid->NK() << std::endl;
    MarchingSquaresGridf phi(*m_grid); 

    m_obj = new Mesh2f();
    phi.populateMesh(*m_obj,0);
    MeshUtils::normalize(*m_obj);
    std::cout << m_obj->vertices.size() << std::endl;
    std::cout << m_obj->faces.size() << std::endl;
    sendBuffers();

}
Beispiel #18
0
inline Polynomial<eT>
polyfit(const eT* x, const eT* y, const uword length, const uword order)
{
    const uword size = order + 1;
    Col<eT> Q(size);   //parameter to be estimated.
    Q.fill(eT(0));        //initialized with zeros.
    Col<eT> phi(size); //
    Mat<eT> P = eye(size, size) * 1e6;
    Col<eT> K;
    Mat<eT> I = eye(size, size);

    for(uword i = 0; i < length; ++i)
    {
        detail::gen_phi(phi, x[i]);
        K = P * phi / (1 + as_scalar(phi.st() * P * phi)); //K(t) = P(t-1)*phi(t)*inv(I+phi'*P(t-1)*phi).
        P = (I - K * phi.st()) * P; //P(t) = (I-K(t)*phi')*P(t-1).
        Q = Q + K * (y[i] - as_scalar(phi.st() * Q)); //Q(t) = Q(t-1) + K(t)*(y(t)-phi'Q(t-1)).
    }
    return std::move(Polynomial<eT>(Q));
}
double PDPS::logpri()const{
  const Mat & Nu(m_->Nu());
  uint d = nrow(Nu);
  Vec phi(d);
  double ans=0;
  for(uint i=0; i<d; ++i){
    double a = sum(Nu.row(i));
    if(a <=0) return BOOM::negative_infinity();
    phi = Nu.row(i);
    for(uint j=0; j<d; ++j) {
      if(phi[j] < min_nu_) {
        return BOOM::negative_infinity();
      }
    }
    phi/=a;
    ans += alpha_row_prior_[i]->logp(a);
    ans += phi_row_prior_[i]->logp(phi);
    ans -= (d-1) * log(a);
  }
  return ans;
}
Beispiel #20
0
/***********************************************************************//**
 * @brief Sum function multiplied by livetime over zenith and azimuth angles
 *
 * @param[in] dir Sky direction.
 * @param[in] fct Function to evaluate.
 *
 * Computes
 * \f[\sum_{\cos \theta, \phi} T_{\rm live}(\cos \theta, \phi) 
 *    f(\cos \theta, \phi)\f]
 * where
 * \f$T_{\rm live}(\cos \theta, \phi)\f$ is the livetime as a function of
 * the cosine of the zenith and of the azimuth angle, and
 * \f$f(\cos \theta, \phi)\f$ is a function that depends on the cosine of
 * the zenith angle and of the azimuth angle.
 * This method assumes that \f$T_{\rm live}(\cos \theta, \phi)\f$ is
 * stored as a set of maps in a 2D array with \f$\cos \theta\f$ being the
 * most rapidely varying parameter and with the first map starting at
 * index m_num_ctheta (the first m_num_ctheta maps are the livetime cube
 * maps without any \f$\phi\f$ dependence).
 ***************************************************************************/
double GLATLtCubeMap::operator()(const GSkyDir& dir, _ltcube_ctheta_phi fct) const
{
    // Get map index
    int pixel = m_map.dir2pix(dir);

    // Initialise sum
    double sum = 0.0;

    // Loop over azimuth and zenith angles. Note that the map index starts
    // with m_num_ctheta as the first m_num_ctheta maps correspond to an
    // evaluation without any phi-dependence.
    for (int iphi = 0, i = m_num_ctheta; iphi < m_num_phi; ++iphi) {
        double p = phi(iphi);
        for (int itheta = 0; itheta < m_num_ctheta; ++itheta, ++i) {
            sum += m_map(pixel, i) * (*fct)(costheta(itheta), p);
        }
    }

    // Return sum
    return sum;
}
// for co-ordinates at box nn, ll, evaluates the value using
// coefficients at box n, l
// this function assumes that x is Vector.
double* FunctionAST::evaluate_at_box(int k, double* coeff, int n, int l, int nn, int ll, double* x)
{
    int         i;
    double*     p;
    double      coordinate;
    double      temp;
    double*     returnVector;


    returnVector    = Vector_initialize(NULL, 0, this->func->k+ADD_K);
    for (i=0; i<this->func->k; i++)
    {
        coordinate          = ((x[i] + ll) * (pow(2.0, n - nn))) - l;
        p                   = Vector_initialize(phi(coordinate, this->func->k), 0, this->func->k);
        temp                = Vector_inner(coeff, p, this->func->k);
        returnVector[i]     = temp * sqrt(pow(2.0, n));

        free(p);
    }
    return returnVector;
}
void oneEqEddy::correct(const tmp<volTensorField>& gradU)
{
    GenEddyVisc::correct(gradU);

    volScalarField G = 2.0*nuSgs_*magSqr(symm(gradU));

    solve
    (
       fvm::ddt(k_)
     + fvm::div(phi(), k_)
     - fvm::laplacian(DkEff(), k_)
    ==
       G
     - fvm::Sp(ce_*sqrt(k_)/delta(), k_)
    );

    bound(k_, k0());

    nuSgs_ = ck_*sqrt(k_)*delta();
    nuSgs_.correctBoundaryConditions();
}
Beispiel #23
0
int run(){

const int order_ = 20;
int numshape = (order_+1)*(order_+1)*(order_+1);

  TPZVec<REAL> point(3,0.);
  TPZVec<int> id(8);
  int i;

  for(i = 0; i< 8; i ++)
  {
  	id[i] = i;
  }

  TPZVec<int> order(19);
  for(i = 0; i< 19; i ++)
  {
        order[i] = order_;
  }

  TPZCompEl::SetgOrder(order_);

  TPZVec<FADREAL> phi(numshape);
  TPZFMatrix OldPhi(numshape,1), OldDPhi(3,numshape);
  TPZFMatrix DiffPhi(numshape,1), DiffDPhi(3,numshape);

  TPZShapeCube::ShapeCube(point, id, order, phi);
  TPZShapeCube::ShapeCube(point, id, order, OldPhi, OldDPhi);

  /*cout << "Calculated by Fad" << phi;
  cout << "Old derivative method (phi)\n" << OldPhi;
  cout << "Old derivative method (dPhi)\n" << OldDPhi;

  shapeFAD::ExplodeDerivatives(phi, DiffPhi, DiffDPhi);
  DiffPhi-=OldPhi;
  DiffDPhi-=OldDPhi;*/
  //cout << "FAD derivative method (phi)\n" << /*TPZFMatrix (OldPhi -*/ DiffPhi;
  //cout << "FAD derivative method (dPhi)\n" <</* TPZFMatrix (OldDPhi -*/ DiffDPhi;
  return 0;
}
void Foam::S_MDCPP::correct()
{
    // Velocity gradient tensor
    volTensorField L = fvc::grad(U());

    // Convected derivate term
    volTensorField C = tau_ & L;

    // Twice the rate of deformation tensor
    volSymmTensorField twoD = twoSymm(L);

    // Lambda (Backbone stretch)
    volScalarField Lambda =
        Foam::sqrt(1 + tr(tau_)*lambdaOb_*(1 - zeta_)/3/etaP_);

    // Auxiliary field
    volScalarField aux = Foam::exp( 2/q_*(Lambda - 1));

    // Extra function
    volScalarField fTau =
        aux*(2*lambdaOb_/lambdaOs_*(1 - 1/Lambda) + 1/Foam::sqr(Lambda));

    // Stress transport equation
    fvSymmTensorMatrix tauEqn
    (
        fvm::ddt(tau_)
        + fvm::div(phi(), tau_)
        ==
        etaP_/lambdaOb_*twoD
        + twoSymm(C)
        - zeta_/2*((tau_ & twoD) + (twoD & tau_))
        - fvm::Sp(1/lambdaOb_*fTau, tau_)
        - (
            1/lambdaOb_*(etaP_/lambdaOb_/(1 - zeta_)*(fTau - aux)*I_)
        )
    );

    tauEqn.relax();
    tauEqn.solve();
}
void CD_Extended_Kalman_Filter::_rk4___prediction_FM(dcovector &Xp, dgematrix &p)
{
      Continuous_Discrete_Model *m=dynamic_cast<Continuous_Discrete_Model *>(model);
      dgematrix G = m->Diffusion_Function();
      dgematrix Q=G*(m->Qw*t(G));
      double delta = m->Ts;
      dgematrix phi(p.m,p.n);
      dcovector  dx1, dx2, dx3, dx4;

      dgematrix K1, K2, K3, K4;

      dgematrix J1,J2,J3,J4;

      dx1 =  m->Drift_Function(M);

      dx2 =  m->Drift_Function(M + 0.5*delta *dx1);

      dx3 =  m->Drift_Function(M + 0.5*delta *dx2);

      dx4 =  m->Drift_Function(M + delta *dx3); 

      Xp= M + delta * (dx1+2.*dx2+2.*dx3+dx4)/6.;


      J1 = m->J_Drift_Function(M);
      J2 = m->J_Drift_Function(M + 0.5 * delta * dx1);
      J3 = m->J_Drift_Function(M + 0.5 * delta * dx2);
      J4 = m->J_Drift_Function(M + delta * dx3);

      phi.identity();
      K1 = J1  ;
      K2 = J2 * (phi + 0.5*delta * K1);
      K3 = J3 * (phi + 0.5*delta * K2);
      K4 = J4 * (phi + delta * K3);

      phi = phi + delta *(K1 + 2.*K2 + 2.*K3 + K4) / 6.;

      p = phi *(R * t(phi)) +  Q  * delta;
}
Beispiel #26
0
obj applyCS(obj (*func)(obj, obj), obj v1, obj v2){
	assert(!isVec(type(v2)));
	if(isVec(type(v1))){
		int len=size(v1);
		obj rr = aArray(len);
		for(int i=0; i<len; i++){
			obj lt=ind(v1,i);
			uar(rr).v[i] = call_fn(func, lt, v2); 
			release(lt);
		}
		return rr;
	}
	if(type(v1)==LIST){
		list l=phi();
		for(list l1=ul(v1); l1; l1=rest(l1)){
			l = cons(call_fn(func, first(l1), v2), l);
		}
		return List2v(reverse(l));
	}
	assert(0);
	return nil;
}
Beispiel #27
0
/** @brief Volumetric contribute with jacobian matrix */
void TPZPrimalPoisson::Contribute(TPZMaterialData &data,REAL weight,TPZFMatrix<STATE> &ek,TPZFMatrix<STATE> &ef){

    TPZFNMatrix<220,REAL> &phi     = data.phi;
    TPZFNMatrix<660,REAL> &dphix   = data.dphix;
    
    TPZFNMatrix<15,STATE> &dpdx    = data.dsol[0];
    
    int nphi_p = phi.Rows();

    TPZManVector<STATE,1> f(1,0.0);
    TPZFMatrix<STATE> df;
    if (this->HasForcingFunction()) {
        this->fForcingFunction->Execute(data.x, f, df);
    }
   
    int dim = this->Dimension();
    
    for (int ip = 0; ip < nphi_p; ip++) {
        
        STATE dp_dot_dphi_i = 0.0;
        for (int i = 0; i < dim; i++) {
            dp_dot_dphi_i += dpdx[i]*dphix(i,ip);
        }
        
        ef(ip,0) += weight * (dp_dot_dphi_i - f[0] * phi(ip,0));
        
        for (int jp = 0; jp < nphi_p; jp++) {
            
            STATE dphi_j_dot_dphi_i = 0.0;
            for (int i = 0; i < this->Dimension(); i++) {
                dphi_j_dot_dphi_i += dphix(i,jp)*dphix(i,ip);
            }
            
            ek(ip,jp) += weight * dphi_j_dot_dphi_i;
        }
        
    }
    
}
Beispiel #28
0
double GMM<FittingType>::LogLikelihood(
    const arma::mat& data,
    const std::vector<arma::vec>& meansL,
    const std::vector<arma::mat>& covariancesL,
    const arma::vec& weightsL) const
{
  double loglikelihood = 0;

  arma::vec phis;
  arma::mat likelihoods(gaussians, data.n_cols);
  for (size_t i = 0; i < gaussians; i++)
  {
    phi(data, meansL[i], covariancesL[i], phis);
    likelihoods.row(i) = weightsL(i) * trans(phis);
  }

  // Now sum over every point.
  for (size_t j = 0; j < data.n_cols; j++)
    loglikelihood += log(accu(likelihoods.col(j)));

  return loglikelihood;
}
int main()
{
    int i,n;
    double p,min=2147483647.0,ph,epsilon=0.000000001;
    for(i=2;i<MAX;i++)
    {
        if(i%100000==0)
            printf("%d\n",i);
        ph=(double)phi(i);
        if(isPermutation(i,ph))
        {
            p=n/ph;
            if(min-p > epsilon)
            {
                min=p;
                n=i;
            }
        }
    }
    printf("answer = %d\n",n);
    return 0;
}
void SpalartAllmaras::correct(const tmp<volTensorField>& gradU)
{
    LESModel::correct(gradU);

    if (mesh_.changing())
    {
        y_.correct();
        y_.boundaryField() = max(y_.boundaryField(), VSMALL);
    }

    const volScalarField S(this->S(gradU));
    const volScalarField dTilda(this->dTilda(S));
    const volScalarField STilda(this->STilda(S, dTilda));

    tmp<fvScalarMatrix> nuTildaEqn
    (
        fvm::ddt(nuTilda_)
      + fvm::div(phi(), nuTilda_)
      - fvm::laplacian
        (
            (nuTilda_ + nu())/sigmaNut_,
            nuTilda_,
            "laplacian(DnuTildaEff,nuTilda)"
        )
      - Cb2_/sigmaNut_*magSqr(fvc::grad(nuTilda_))
     ==
        Cb1_*STilda*nuTilda_
      - fvm::Sp(Cw1_*fw(STilda, dTilda)*nuTilda_/sqr(dTilda), nuTilda_)
    );

    nuTildaEqn().relax();
    nuTildaEqn().solve();

    bound(nuTilda_, dimensionedScalar("zero", nuTilda_.dimensions(), 0.0));
    nuTilda_.correctBoundaryConditions();

    updateSubGridScaleFields();
}