Fp operator-(const Fp& me, const Fp& rhs) {
  mpz_class c = me.x - rhs.x;
  if (c > 0) {
    return c;
  }
    return Fp(c + Fp::p);
}
  void LowMachNavierStokes<Mu,SH,TC>::assemble_mass_time_deriv( bool /*compute_jacobian*/, 
								AssemblyContext& context,
								CachedValues& cache )
  {
    // The number of local degrees of freedom in each variable.
    const unsigned int n_p_dofs = context.get_dof_indices(this->_p_var).size();

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

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

    libMesh::DenseSubVector<libMesh::Number> &Fp = context.get_elem_residual(this->_p_var); // R_{p}

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

    for (unsigned int qp=0; qp != n_qpoints; qp++)
      {
	libMesh::Number u, v, T;
	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];

	libMesh::Gradient grad_u = cache.get_cached_gradient_values(Cache::X_VELOCITY_GRAD)[qp];
	libMesh::Gradient grad_v = cache.get_cached_gradient_values(Cache::Y_VELOCITY_GRAD)[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 divU = grad_u(0) + grad_v(1);
	if (this->_dim == 3)
          {
	    libMesh::Gradient grad_w = cache.get_cached_gradient_values(Cache::Z_VELOCITY_GRAD)[qp];
	    divU += grad_w(2);
          }

	// Now a loop over the pressure degrees of freedom.  This
	// computes the contributions of the continuity equation.
	for (unsigned int i=0; i != n_p_dofs; i++)
	  {
	    Fp(i) += (-U*grad_T/T + divU)*p_phi[i][qp]*JxW[qp];
	  }
      }

    return;
  }
Expression* sintactico::Fp()
{
    if(CurrentToken->tipo == PORCENTAJE)
    {
        CurrentToken = Lexer->NexToken();
        Expression* izq = G();
        Expression* der = Fp();
        if(der != NULL)
            return new exprMode(izq,der,Lexer->linea);
        return izq;
    }
    return NULL;
}
void LowMachNavierStokesSPGSMStabilization<Mu,SH,TC>::assemble_continuity_time_deriv( bool /*compute_jacobian*/,
        AssemblyContext& context )
{
    // The number of local degrees of freedom in each variable.
    const unsigned int n_p_dofs = context.get_dof_indices(this->_press_var.p()).size();

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

    // The pressure shape functions at interior quadrature points.
    const std::vector<std::vector<libMesh::RealGradient> >& p_dphi =
        context.get_element_fe(this->_press_var.p())->get_dphi();

    libMesh::DenseSubVector<libMesh::Number> &Fp = context.get_elem_residual(this->_press_var.p()); // R_{p}

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

    for (unsigned int qp=0; qp != n_qpoints; qp++)
    {
        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 T = context.interior_value( this->_temp_vars.T(), qp );

        libMesh::Real mu = this->_mu(T);

        libMesh::Real rho = this->rho( T, this->get_p0_steady( context, qp ) );

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

        libMesh::Real tau_M = this->_stab_helper.compute_tau_momentum( context, qp, g, G, rho, U, mu, this->_is_steady );

        libMesh::RealGradient RM_s = this->compute_res_momentum_steady( context, qp );

        // Now a loop over the pressure degrees of freedom.  This
        // computes the contributions of the continuity equation.
        for (unsigned int i=0; i != n_p_dofs; i++)
        {
            Fp(i) += tau_M*RM_s*p_dphi[i][qp]*JxW[qp];
        }

    }

    return;
}
Beispiel #5
0
// Right-hand side of the Lax-Wendroff discretization:
//
//      ( q(t+dt) - q(t) )/dt = -F_{x} - G_{y}.
//
// This routine constructs the 'time-integrated' flux functions F and G using the
// Cauchy-Kowalewski procedure.
//
// First, consider time derivatives of q
//
//    q^{n+1} = q^n + dt * (q^n_t + dt/2 * q^n_tt + dt^3/6 q^n_ttt ).
//
// Formally, these are given by
//
//   q_{t}    = ( -f(q) )_x + ( -g(q) )_y, 
//   q_{tt}   = ( f'(q) * ( f_x + g_y )_x + ( g'(q) * ( f_x + g_y )_y
//   q_{ttt}  = ...
//
// Now, considering Taylor expansions of f and g, centered about t = t^n
//
//  F = f^n + (t-t^n) \dot{f^n} + \cdots
//  G = g^n + (t-t^n) \dot{g^n} + \cdots
//
// We have the following form, after integrating in time
//
//  F: = ( f - dt/2 * ( f'(q)*( f_x+g_y ) 
//           + dt^2/6 ( \pd2{f}{q} \cdot (f_x+g_y,f_x+g_y) +
//                        \pd{f}{q} (  f_x + g_y )_t  ) + \cdots
//
//  G: = ( g - dt/2 * ( g'(q)*( f_x+g_y )
//           + dt^2/6 ( \pd2{g}{q} \cdot (f_x+g_y,f_x+g_y) +
//                        \pd{g}{q} (  f_x + g_y )_t ) + \cdots
//
// where the final ingredient is
//
//  (f_x+g_y)_t = \pd2{f}{q} \cdot (q_x, f_x+g_y ) + \pd{f}{q} ( f_xx + g_xy ) +
//                \pd2{g}{q} \cdot (q_y, f_x+g_y ) + \pd{g}{q} ( f_xy + g_yy ).
//
// At the end of the day, we set
//
//    L(q) := -F_x - G_y.
//
// See also: ConstructL.
void LaxWendroff(double dt, 
    const dTensorBC4& aux, const dTensorBC4& q,    // set bndy values modifies these
    dTensorBC4& Lstar, dTensorBC3& smax)
{

printf("This call hasn't been tested \n");

    if ( !dogParams.get_flux_term() )
    {  return;  }

    const edge_data& edgeData = Legendre2d::get_edgeData();
    const int space_order = dogParams.get_space_order();
    const int mx   = q.getsize(1);
    const int my   = q.getsize(2);
    const int meqn = q.getsize(3);
    const int kmax = q.getsize(4);
    const int mbc  = q.getmbc();
    const int maux = aux.getsize(3);

    // Flux values
    //
    // Space-order = number of quadrature points needed for 1D integration
    // along cell edges.
    //
    dTensorBC4 Fm(mx, my, meqn, space_order, mbc);
    dTensorBC4 Fp(mx, my, meqn, space_order, mbc);
    dTensorBC4 Gm(mx, my, meqn, space_order, mbc);
    dTensorBC4 Gp(mx, my, meqn, space_order, mbc);

    // Flux function
    void FluxFunc(const dTensor2& xpts,
                  const dTensor2& Q,
                  const dTensor2& Aux,
                  dTensor3& flux);

    // Jacobian of the flux function:
    void DFluxFunc(const dTensor2& xpts, 
                   const dTensor2& Q,
                   const dTensor2& Aux, 
                   dTensor4& Dflux );

    // Hessian of the flux function:
    void D2FluxFunc(const dTensor2& xpts, 
                   const dTensor2& Q,
                   const dTensor2& Aux, 
                   dTensor5& D2flux );


    // Riemann solver that relies on the fact that we already have 
    // f(ql) and f(qr) already computed:
    double RiemannSolveLxW(const dTensor1& nvec,
        const dTensor1& xedge,
        const dTensor1& Ql,   const dTensor1& Qr,
        const dTensor1& Auxl, const dTensor1& Auxr,
        const dTensor1& ffl,  const dTensor1& ffr,
        dTensor1& Fl, dTensor1& Fr);

    void LstarExtra(const dTensorBC4*,
            const dTensorBC4*,
            dTensorBC4*);
    void ArtificialViscosity(const dTensorBC4* aux, 
            const dTensorBC4* q, 
            dTensorBC4* Lstar);

    // Grid information
    const double xlower = dogParamsCart2.get_xlow();
    const double ylower = dogParamsCart2.get_ylow();
    const double dx = dogParamsCart2.get_dx();
    const double dy = dogParamsCart2.get_dy();

    // --------------------------------------------------------------------- //
    // Boundary data:
    // --------------------------------------------------------------------- //
    // TODO - call this routine before calling this function.
//  void SetBndValues(dTensorBC4& q, dTensorBC4& aux);
//  SetBndValues(q, aux);
    // ---------------------------------------------------------

    // --------------------------------------------------------------------- //
    // Part 0: Compute the Lax-Wendroff "flux" function:
    //
    // Here, we include the extra information about time derivatives.
    // --------------------------------------------------------------------- //
    dTensorBC4 F(mx, my, meqn, kmax, mbc);  F.setall(0.);
    dTensorBC4 G(mx, my, meqn, kmax, mbc);  G.setall(0.);
    void L2ProjectLxW( const int mterms, 
        const double alpha, const double beta_dt, const double charlie_dt,
        const int istart, const int iend, 
        const int jstart, const int jend,
        const int QuadOrder,
        const int BasisOrder_auxin,
        const int BasisOrder_fout,    
        const dTensorBC4* qin,
        const dTensorBC4* auxin,
        dTensorBC4* F,
        dTensorBC4* G,
        void FluxFunc (const dTensor2& xpts, 
            const dTensor2& Q, const dTensor2& Aux, dTensor3& flux),
        void DFluxFunc (const dTensor2& xpts, 
            const dTensor2& Q, const dTensor2& aux, dTensor4& Dflux),
        void D2FluxFunc (const dTensor2& xpts, 
            const dTensor2& Q, const dTensor2& aux, dTensor5& D2flux) );
printf("hello\n");
    L2ProjectLxW( 3, 1.0, 0.5*dt, dt*dt/6.0,
        1-mbc, mx+mbc, 1-mbc, my+mbc,
        space_order, space_order, space_order,
        &q, &aux, &F, &G, &FluxFunc, &DFluxFunc, D2FluxFunc );

    // ---------------------------------------------------------
    // Part I: compute source term
    // --------------------------------------------------------- 
    if( dogParams.get_source_term() > 0 )
    {
        // eprintf("error: have not implemented source term for LxW solver.");
        printf("Source term has not been implemented for LxW solver.  Terminating program.");
        exit(1);
    }
    Lstar.setall( 0. );

    // ---------------------------------------------------------
    // Part II: compute inter-element interaction fluxes
    //
    //   N = int( F(q,x,t) * phi_x, x ) / dA
    //
    // ---------------------------------------------------------

    // 1-direction: loop over interior edges and solve Riemann problems
    dTensor1 nvec(2);
    nvec.set(1, 1.0e0 );
    nvec.set(2, 0.0e0 );

#pragma omp parallel for
    for (int i=(2-mbc); i<=(mx+mbc); i++)
    {

        dTensor1 Ql(meqn),   Qr(meqn);
        dTensor1 ffl(meqn),  ffr(meqn);
        dTensor1 Fl(meqn),   Fr(meqn);
        dTensor1 DFl(meqn),  DFr(meqn);
        dTensor1 Auxl(maux), Auxr(maux);

        dTensor1 xedge(2);

        for (int j=(2-mbc); j<=(my+mbc-1); j++)
        {
            // ell indexes Riemann point along the edge
            for (int ell=1; ell<=space_order; ell++)
            {
                // Riemann data - q and f (from basis functions/q)
                for (int m=1; m<=meqn; m++)
                {
                    Ql.set (m, 0.0 );
                    Qr.set (m, 0.0 );
                    ffl.set(m, 0.0 );
                    ffr.set(m, 0.0 );

                    for (int k=1; k<=kmax; k++)
                    {
                        // phi_xl( xi=1.0, eta ), phi_xr( xi=-1.0, eta )
                        Ql.fetch(m)  += edgeData.phi_xl->get(ell,k)*q.get(i-1, j, m, k );
                        Qr.fetch(m)  += edgeData.phi_xr->get(ell,k)*q.get(i,   j, m, k );
                        ffl.fetch(m) += edgeData.phi_xl->get(ell,k)*F.get(i-1, j, m, k );
                        ffr.fetch(m) += edgeData.phi_xr->get(ell,k)*F.get(i,   j, m, k );
                    }

                }

                // Riemann data - aux
                for (int m=1; m<=maux; m++)
                {
                    Auxl.set(m, 0.0 );
                    Auxr.set(m, 0.0 );

                    for (int k=1; k<=kmax; k++)
                    {
                        Auxl.fetch(m) += edgeData.phi_xl->get(ell,k)*aux.get(i-1, j, m, k);
                        Auxr.fetch(m) += edgeData.phi_xr->get(ell,k)*aux.get(i,   j, m, k);
                    }
                }

                // Solve Riemann problem
                xedge.set(1, xlower + (double(i)-1.0)*dx );
                xedge.set(2, ylower + (double(j)-0.5)*dy );

                const double smax_edge = RiemannSolveLxW(
                    nvec, xedge, Ql, Qr, Auxl, Auxr, ffl, ffr, Fl, Fr);

                smax.set(i-1, j, 1, Max(dy*smax_edge,smax.get(i-1, j, 1)) );
                smax.set(i,   j, 1, Max(dy*smax_edge,smax.get(i,   j, 1)) );

                // Construct fluxes
                for (int m=1; m<=meqn; m++)
                {
                    Fm.set(i  , j, m, ell,  Fr.get(m) );
                    Fp.set(i-1, j, m, ell,  Fl.get(m) );
                }
            }
        }
    }


    // 2-direction: loop over interior edges and solve Riemann problems
    nvec.set(1, 0.0e0 );
    nvec.set(2, 1.0e0 );

#pragma omp parallel for
    for (int i=(2-mbc); i<=(mx+mbc-1); i++)
    {
        dTensor1  Ql(meqn),   Qr(meqn);
        dTensor1  Fl(meqn),   Fr(meqn);
        dTensor1 ffl(meqn),  ffr(meqn);
        dTensor1 Auxl(maux),Auxr(maux);
        dTensor1 xedge(2);

        for (int j=(2-mbc); j<=(my+mbc); j++)
        for (int ell=1; ell<=space_order; ell++)
        {
            // Riemann data - q
            for (int m=1; m<=meqn; m++)
            {

                Ql.set  (m, 0.0 );
                Qr.set  (m, 0.0 );
                ffl.set (m, 0.0 );
                ffr.set (m, 0.0 );

                for (int k=1; k<=kmax; k++)
                {
                    Ql.fetch(m)  += edgeData.phi_yl->get(ell, k)*q.get(i, j-1, m, k );
                    Qr.fetch(m)  += edgeData.phi_yr->get(ell, k)*q.get(i, j,   m, k );
                    ffl.fetch(m) += edgeData.phi_yl->get(ell, k)*G.get(i, j-1, m, k );
                    ffr.fetch(m) += edgeData.phi_yr->get(ell, k)*G.get(i,   j, m, k );
                }
            }

            // Riemann data - aux
            for (int m=1; m<=maux; m++)
            {
                Auxl.set(m, 0.0 );
                Auxr.set(m, 0.0 );

                for (int k=1; k<=kmax; k++)
                {
                    Auxl.fetch(m) += edgeData.phi_yl->get(ell,k)*aux.get(i,j-1,m,k);
                    Auxr.fetch(m) += edgeData.phi_yr->get(ell,k)*aux.get(i,j,m,k);
                }
            }

            // Solve Riemann problem
            xedge.set(1, xlower + (double(i)-0.5)*dx );
            xedge.set(2, ylower + (double(j)-1.0)*dy );

            const double smax_edge = RiemannSolveLxW(
                nvec, xedge, Ql, Qr, Auxl, Auxr, ffl, ffr, Fl, Fr);

            smax.set(i, j-1, 2,  Max(dx*smax_edge, smax.get(i, j-1, 2)) );
            smax.set(i, j,   2,  Max(dx*smax_edge, smax.get(i, j,   2)) );

            // Construct fluxes
            for (int m=1; m<=meqn; m++)
            {
                Gm.set(i, j,   m, ell, Fr.get(m) );
                Gp.set(i, j-1, m, ell, Fl.get(m) );
            }
        }
    }

    // Compute ``flux differences'' dF and dG    
    const double half_dx_inv = 0.5/dx;
    const double half_dy_inv = 0.5/dy;
    const int mlength = Lstar.getsize(3);   assert_eq( meqn, mlength );

    // Use the four values, Gm, Gp, Fm, Fp to construct the boundary integral:
#pragma omp parallel for
    for (int i=(2-mbc); i<=(mx+mbc-1); i++)    
    for (int j=(2-mbc); j<=(my+mbc-1); j++)
    for (int m=1; m<=mlength; m++)
    for (int k=1; k<=kmax; k++)
    {
        // 1-direction: dF
        double F1 = 0.0;
        double F2 = 0.0;
        for (int ell=1; ell<=space_order; ell++)
        {
            F1 = F1 + edgeData.wght_phi_xr->get(ell,k)*Fm.get(i,j,m,ell);
            F2 = F2 + edgeData.wght_phi_xl->get(ell,k)*Fp.get(i,j,m,ell);
        }

        // 2-direction: dG
        double G1 = 0.0;
        double G2 = 0.0;
        for (int ell=1; ell<=space_order; ell++)
        {
            G1 = G1 + edgeData.wght_phi_yr->get(ell,k)*Gm.get(i,j,m,ell);
            G2 = G2 + edgeData.wght_phi_yl->get(ell,k)*Gp.get(i,j,m,ell);
        }

        Lstar.fetch(i,j,m,k) -= (half_dx_inv*(F2-F1) + half_dy_inv*(G2-G1));

    }
    // ---------------------------------------------------------


    // ---------------------------------------------------------
    // Part III: compute intra-element contributions
    // ---------------------------------------------------------
    // No need to call this if first-order in space
    if(dogParams.get_space_order()>1)
    {

        dTensorBC4 Ltmp( mx, my, meqn, kmax, mbc );
        void L2ProjectGradAddLegendre(const int istart, 
                const int iend, 
                const int jstart, 
                const int jend,
                const int QuadOrder, 
                const dTensorBC4* F, 
                const dTensorBC4* G, 
                dTensorBC4* fout );
        L2ProjectGradAddLegendre( 1-mbc, mx+mbc, 1-mbc, my+mbc,
            space_order, &F, &G, &Lstar );

    }
    // ---------------------------------------------------------  

    // ---------------------------------------------------------
    // Part IV: add extra contributions to Lstar
    // ---------------------------------------------------------
    // Call LstarExtra
    LstarExtra(&q,&aux,&Lstar);
    // ---------------------------------------------------------


    // ---------------------------------------------------------
    // Part V: artificial viscosity limiter
    // ---------------------------------------------------------  
    if (dogParams.get_space_order()>1  &&
            dogParams.using_viscosity_limiter())
    {  ArtificialViscosity(&aux,&q,&Lstar);  }
    // ---------------------------------------------------------

}
bool operator==(const Fp& me, const int rhs){
  return me == Fp(rhs);
}
Fp operator*(const Fp& me, const Fp& rhs) {
  return Fp(me.x * rhs.x);
}
Fp operator-(const Fp& me) {
  return Fp(-me.x) + Fp::p;
}
  void VelocityPenaltyAdjointStabilization<Mu>::element_constraint( bool compute_jacobian,
                                                                AssemblyContext& context,
                                                                CachedValues& /*cache*/ )
  {
#ifdef GRINS_USE_GRVY_TIMERS
    this->_timer->BeginTimer("VelocityPenaltyAdjointStabilization::element_constraint");
#endif

    // The number of local degrees of freedom in each variable.
    const unsigned int n_p_dofs = context.get_dof_indices(this->_press_var.p()).size();
    const unsigned int n_u_dofs = context.get_dof_indices(this->_flow_vars.u()).size();

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

    const std::vector<libMesh::Point>& u_qpoint = 
      context.get_element_fe(this->_flow_vars.u())->get_xyz();

    const std::vector<std::vector<libMesh::Real> >& u_phi =
      context.get_element_fe(this->_flow_vars.u())->get_phi();

    const std::vector<std::vector<libMesh::RealGradient> >& p_dphi =
      context.get_element_fe(this->_press_var.p())->get_dphi();

    libMesh::DenseSubVector<libMesh::Number> &Fp = context.get_elem_residual(this->_press_var.p()); // R_{p}

    libMesh::DenseSubMatrix<libMesh::Number> &Kpu = 
      context.get_elem_jacobian(this->_press_var.p(), this->_flow_vars.u()); // J_{pu}
    libMesh::DenseSubMatrix<libMesh::Number> &Kpv = 
      context.get_elem_jacobian(this->_press_var.p(), this->_flow_vars.v()); // J_{pv}
    libMesh::DenseSubMatrix<libMesh::Number> *Kpw = NULL;
 
    if(this->mesh_dim(context) == 3)
      {
        Kpw = &context.get_elem_jacobian
          (this->_press_var.p(), this->_flow_vars.w()); // J_{pw}
      }

    // 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();

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

    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->mesh_dim(context) == 3 )
          {
            U(2) = context.interior_value( this->_flow_vars.w(), qp );
          }

        // Compute the viscosity at this qp
        libMesh::Real mu_qp = this->_mu(context, qp);

        libMesh::Real tau_M;
        libMesh::Real d_tau_M_d_rho;
        libMesh::Gradient d_tau_M_dU;

        if (compute_jacobian)
          this->_stab_helper.compute_tau_momentum_and_derivs
            ( context, qp, g, G, this->_rho, U, mu_qp,
              tau_M, d_tau_M_d_rho, d_tau_M_dU,
              this->_is_steady );
        else
          tau_M = this->_stab_helper.compute_tau_momentum
                    ( context, qp, g, G, this->_rho, U, mu_qp,
                      this->_is_steady );

        libMesh::NumberVectorValue F;
        libMesh::NumberTensorValue dFdU;
        libMesh::NumberTensorValue* dFdU_ptr =
          compute_jacobian ? &dFdU : NULL;
        if (!this->compute_force(u_qpoint[qp], context, U, F, dFdU_ptr))
          continue;

        // First, an i-loop over the velocity degrees of freedom.
        // We know that n_u_dofs == n_v_dofs so we can compute contributions
        // for both at the same time.
        for (unsigned int i=0; i != n_p_dofs; i++)
          {
            Fp(i) += -tau_M*F*p_dphi[i][qp]*JxW[qp];

            if (compute_jacobian)
              {
                for (unsigned int j=0; j != n_u_dofs; ++j)
                  {
                    Kpu(i,j) += -d_tau_M_dU(0)*u_phi[j][qp]*F*p_dphi[i][qp]*JxW[qp]*context.get_elem_solution_derivative();
                    Kpv(i,j) += -d_tau_M_dU(1)*u_phi[j][qp]*F*p_dphi[i][qp]*JxW[qp]*context.get_elem_solution_derivative();
                    for (unsigned int d=0; d != 3; ++d)
                      {
                        Kpu(i,j) += -tau_M*dFdU(d,0)*u_phi[j][qp]*p_dphi[i][qp](d)*JxW[qp]*context.get_elem_solution_derivative();
                        Kpv(i,j) += -tau_M*dFdU(d,1)*u_phi[j][qp]*p_dphi[i][qp](d)*JxW[qp]*context.get_elem_solution_derivative();
                      }
                  }
                if( this->mesh_dim(context) == 3 )
                  for (unsigned int j=0; j != n_u_dofs; ++j)
                    {
                      (*Kpw)(i,j) += -d_tau_M_dU(2)*u_phi[j][qp]*F*p_dphi[i][qp]*JxW[qp]*context.get_elem_solution_derivative();
                      for (unsigned int d=0; d != 3; ++d)
                        {
                          (*Kpw)(i,j) += -tau_M*dFdU(d,2)*u_phi[j][qp]*p_dphi[i][qp](d)*JxW[qp]*context.get_elem_solution_derivative();
                        }
                    }
              }
          }
      } // End quadrature loop

#ifdef GRINS_USE_GRVY_TIMERS
    this->_timer->EndTimer("VelocityPenaltyAdjointStabilization::element_constraint");
#endif

    return;
  }
void assemble_postvars_rhs (EquationSystems& es,
                      const std::string& system_name)
{

  const Real E    = es.parameters.get<Real>("E");
  const Real NU    = es.parameters.get<Real>("NU");
  const Real KPERM    = es.parameters.get<Real>("KPERM");
  
	Real sum_jac_postvars=0;
	
	Real av_pressure=0;
	Real total_volume=0;

#include "assemble_preamble_postvars.cpp"

  for ( ; el != end_el; ++el)
    {    
 
      const Elem* elem = *el;

      dof_map.dof_indices (elem, dof_indices);
      dof_map.dof_indices (elem, dof_indices_u, u_var);
      dof_map.dof_indices (elem, dof_indices_v, v_var);
      dof_map.dof_indices (elem, dof_indices_p, p_var);
      dof_map.dof_indices (elem, dof_indices_x, x_var);
      dof_map.dof_indices (elem, dof_indices_y, y_var);
      #if THREED
      dof_map.dof_indices (elem, dof_indices_w, w_var);
      dof_map.dof_indices (elem, dof_indices_z, z_var);
      #endif

      const unsigned int n_dofs   = dof_indices.size();
      const unsigned int n_u_dofs = dof_indices_u.size(); 
      const unsigned int n_v_dofs = dof_indices_v.size();
      const unsigned int n_p_dofs = dof_indices_p.size();
      const unsigned int n_x_dofs = dof_indices_x.size(); 
      const unsigned int n_y_dofs = dof_indices_y.size();
      #if THREED
      const unsigned int n_w_dofs = dof_indices_w.size();
      const unsigned int n_z_dofs = dof_indices_z.size();
      #endif
      
      fe_disp->reinit  (elem);
      fe_vel->reinit  (elem);
      fe_pres->reinit (elem);

      Ke.resize (n_dofs, n_dofs);
      Fe.resize (n_dofs);

      Kuu.reposition (u_var*n_u_dofs, u_var*n_u_dofs, n_u_dofs, n_u_dofs);
      Kuv.reposition (u_var*n_u_dofs, v_var*n_u_dofs, n_u_dofs, n_v_dofs);
      Kup.reposition (u_var*n_u_dofs, p_var*n_u_dofs, n_u_dofs, n_p_dofs);
      Kux.reposition (u_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs , n_u_dofs, n_x_dofs);
      Kuy.reposition (u_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_u_dofs, n_y_dofs);
      #if THREED
      Kuw.reposition (u_var*n_u_dofs, w_var*n_u_dofs, n_u_dofs, n_w_dofs);
      Kuz.reposition (u_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_u_dofs, n_z_dofs);
      #endif

      Kvu.reposition (v_var*n_v_dofs, u_var*n_v_dofs, n_v_dofs, n_u_dofs);
      Kvv.reposition (v_var*n_v_dofs, v_var*n_v_dofs, n_v_dofs, n_v_dofs);
      Kvp.reposition (v_var*n_v_dofs, p_var*n_v_dofs, n_v_dofs, n_p_dofs);
      Kvx.reposition (v_var*n_v_dofs, p_var*n_u_dofs + n_p_dofs , n_v_dofs, n_x_dofs);
      Kvy.reposition (v_var*n_v_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_v_dofs, n_y_dofs);
      #if THREED
      Kvw.reposition (v_var*n_u_dofs, w_var*n_u_dofs, n_v_dofs, n_w_dofs);
      Kuz.reposition (v_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_u_dofs, n_z_dofs);
      #endif

      #if THREED
      Kwu.reposition (w_var*n_w_dofs, u_var*n_v_dofs, n_v_dofs, n_u_dofs);
      Kwv.reposition (w_var*n_w_dofs, v_var*n_v_dofs, n_v_dofs, n_v_dofs);
      Kwp.reposition (w_var*n_w_dofs, p_var*n_v_dofs, n_v_dofs, n_p_dofs);
      Kwx.reposition (w_var*n_w_dofs, p_var*n_u_dofs + n_p_dofs , n_v_dofs, n_x_dofs);
      Kwy.reposition (w_var*n_w_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_v_dofs, n_y_dofs);
      Kww.reposition (w_var*n_w_dofs, w_var*n_u_dofs, n_v_dofs, n_w_dofs);
      Kwz.reposition (w_var*n_w_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_u_dofs, n_z_dofs);
      #endif

      Kpu.reposition (p_var*n_u_dofs, u_var*n_u_dofs, n_p_dofs, n_u_dofs);
      Kpv.reposition (p_var*n_u_dofs, v_var*n_u_dofs, n_p_dofs, n_v_dofs);
      Kpp.reposition (p_var*n_u_dofs, p_var*n_u_dofs, n_p_dofs, n_p_dofs);
      Kpx.reposition (p_var*n_v_dofs, p_var*n_u_dofs + n_p_dofs , n_p_dofs, n_x_dofs);
      Kpy.reposition (p_var*n_v_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_p_dofs, n_y_dofs);
      #if THREED
      Kpw.reposition (p_var*n_u_dofs, w_var*n_u_dofs, n_p_dofs, n_w_dofs);
      Kpz.reposition (p_var*n_u_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_p_dofs, n_z_dofs);
      #endif

      Kxu.reposition (p_var*n_u_dofs + n_p_dofs, u_var*n_u_dofs, n_x_dofs, n_u_dofs);
      Kxv.reposition (p_var*n_u_dofs + n_p_dofs, v_var*n_u_dofs, n_x_dofs, n_v_dofs);
      Kxp.reposition (p_var*n_u_dofs + n_p_dofs, p_var*n_u_dofs, n_x_dofs, n_p_dofs);
      Kxx.reposition (p_var*n_u_dofs + n_p_dofs, p_var*n_u_dofs + n_p_dofs , n_x_dofs, n_x_dofs);
      Kxy.reposition (p_var*n_u_dofs + n_p_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_x_dofs, n_y_dofs);
      #if THREED
      Kxw.reposition (p_var*n_u_dofs + n_p_dofs, w_var*n_u_dofs, n_x_dofs, n_w_dofs);
      Kxz.reposition (p_var*n_u_dofs + n_p_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_x_dofs, n_z_dofs);
      #endif


      Kyu.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, u_var*n_u_dofs, n_y_dofs, n_u_dofs);
      Kyv.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, v_var*n_u_dofs, n_y_dofs, n_v_dofs);
      Kyp.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, p_var*n_u_dofs, n_y_dofs, n_p_dofs);
      Kyx.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, p_var*n_u_dofs + n_p_dofs , n_y_dofs, n_x_dofs);
      Kyy.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_y_dofs, n_y_dofs);
      #if THREED
      Kyw.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, w_var*n_u_dofs, n_x_dofs, n_w_dofs);
      Kyz.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_x_dofs, n_z_dofs);
      #endif

      #if THREED
      Kzu.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, u_var*n_u_dofs, n_y_dofs, n_u_dofs);
      Kzv.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, v_var*n_u_dofs, n_y_dofs, n_v_dofs);
      Kzp.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, p_var*n_u_dofs, n_y_dofs, n_p_dofs);
      Kzx.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, p_var*n_u_dofs + n_p_dofs , n_y_dofs, n_x_dofs);
      Kzy.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, p_var*n_u_dofs + n_p_dofs+n_x_dofs , n_y_dofs, n_y_dofs);
      Kzw.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, w_var*n_u_dofs, n_x_dofs, n_w_dofs);
      Kzz.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, p_var*n_u_dofs + n_p_dofs+2*n_x_dofs , n_x_dofs, n_z_dofs);
      #endif



      Fu.reposition (u_var*n_u_dofs, n_u_dofs);
      Fv.reposition (v_var*n_u_dofs, n_v_dofs);
      Fp.reposition (p_var*n_u_dofs, n_p_dofs);
      Fx.reposition (p_var*n_u_dofs + n_p_dofs, n_x_dofs);
      Fy.reposition (p_var*n_u_dofs + n_p_dofs+n_x_dofs, n_y_dofs);
      #if THREED
      Fw.reposition (w_var*n_u_dofs, n_w_dofs);
      Fz.reposition (p_var*n_u_dofs + n_p_dofs+2*n_x_dofs, n_y_dofs);
      #endif
    
	    std::vector<unsigned int> undefo_index;
		  PoroelasticConfig material(dphi,psi);

		
      // Now we will build the element matrix.
      for (unsigned int qp=0; qp<qrule.n_points(); qp++)
        {       
		  
		  
		  Number   p_solid = 0.;

		  grad_u_mat(0) = grad_u_mat(1) = grad_u_mat(2) = 0;
		
		  for (unsigned int d = 0; d < dim; ++d) {
			std::vector<Number> u_undefo;
			std::vector<Number> u_undefo_ref;

			//Fills the vector di with the global degree of freedom indices for the element. :dof_indicies
			
			

			
			Last_non_linear_soln.get_dof_map().dof_indices(elem, undefo_index,d);
			Last_non_linear_soln.current_local_solution->get(undefo_index, u_undefo);
			reference.current_local_solution->get(undefo_index, u_undefo_ref);

			for (unsigned int l = 0; l != n_u_dofs; l++){
			   grad_u_mat(d).add_scaled(dphi[l][qp], u_undefo[l]+u_undefo_ref[l]); 
			}
		  }
          
		  for (unsigned int l=0; l<n_p_dofs; l++)
		  {
			p_solid += psi[l][qp]*Last_non_linear_soln.current_local_solution->el(dof_indices_p[l]);
		}
		
		Point rX;
		material.init_for_qp(rX,grad_u_mat, p_solid, qp,0, p_solid,es);
		Real J=material.J;
		 Real I_1=material.I_1;
		 Real I_2=material.I_2;
		 Real I_3=material.I_3;
		 RealTensor sigma=material.sigma;
		 
		 av_pressure=av_pressure + p_solid*JxW[qp];
		 
		 /*
		 		 		std::cout<<"grad_u_mat(0)" << grad_u_mat(0) <<std::endl;

		 		std::cout<<" J " << J <<std::endl;

		std::cout<<" sigma " << sigma <<std::endl;
		*/
		 Real sigma_sum_sq=pow(sigma(0,0)*sigma(0,0)+sigma(0,1)*sigma(0,1)+sigma(0,2)*sigma(0,2)+sigma(1,0)*sigma(1,0)+sigma(1,1)*sigma(1,1)+sigma(1,2)*sigma(1,2)+sigma(2,0)*sigma(2,0)+sigma(2,1)*sigma(2,1)+sigma(2,2)*sigma(2,2),0.5);
		 
		// std::cout<<" J " << J <<std::endl;


		 sum_jac_postvars=sum_jac_postvars+JxW[qp];
 

		
		for (unsigned int i=0; i<n_u_dofs; i++){
          Fu(i) += I_1*JxW[qp]*phi[i][qp];
          Fv(i) += I_2*JxW[qp]*phi[i][qp];
          Fw(i) += I_3*JxW[qp]*phi[i][qp];

	        Fx(i) += sigma_sum_sq*JxW[qp]*phi[i][qp];
          Fy(i) += J*JxW[qp]*phi[i][qp];
          Fz(i) += 0*JxW[qp]*phi[i][qp];
    }
    
    
 
		for (unsigned int i=0; i<n_p_dofs; i++){
            Fp(i) += J*JxW[qp]*psi[i][qp];
		}
    
          

          
          
} // end qp





  system.rhs->add_vector(Fe, dof_indices);

  system.matrix->add_matrix (Ke, dof_indices);

} // end of element loop
  
	
    system.matrix->close();
    system.rhs->close();



    std::cout<<"Assemble postvars rhs->l2_norm () "<<system.rhs->l2_norm ()<<std::endl;

		
	 std::cout<<"sum_jac   "<< sum_jac_postvars <<std::endl;
	 
	  std::cout<<"av_pressure   "<< av_pressure/sum_jac_postvars <<std::endl;

  return;
}
Beispiel #11
0
void testGeometry() {
    cout << "running testGeometry" << endl;
    cout << "Creating Variables" << endl;

    // Variable Declarations
    // Points
    const Point a = Point(0, 0), b = Point(100, 100), c = Point(0, 100);
    const Point e = Point(200, 0), d = Point(100, 0), f = Point(100, 200);
    // Poly's
    const cnt tri {a, e, b};  // non-equal sides
    const cnt square {a, c, b, d};
    const cnt rect {a, c*2, f, d};
    const cnt bigSquare {a*2-b, c*2-b, b*2-b, d*2-b};
    // Fp's
    const Fp testFp1 = Fp({bigSquare, square});
    const Fp testFp2 = Fp({bigSquare});  // not a valid Fp
    const Fp testFp3 = Fp({square});  // not a valid Fp

    cout << "Creating Vectors" << endl;

    // Vectors
    // Poly's
    const vector<cnt> vpoly1 {tri, square, bigSquare};
    const vector<cnt> vpoly2 {tri, square};
    const vector<cnt> vpoly3 {square, bigSquare};
    const vector<cnt> vpoly4 {tri, bigSquare};
    const vector<cnt> vpoly5 {tri};
    const vector<cnt> vpoly6 {square};
    const vector<cnt> vpoly7 {bigSquare};
    // Fp's
    const vector<Fp> vfp1 {testFp1, testFp2, testFp3};
    const vector<Fp> vfp2 {testFp1, testFp2};
    const vector<Fp> vfp3 {testFp2, testFp3};
    const vector<Fp> vfp4 {testFp1, testFp3};
    const vector<Fp> vfp5 {testFp1};
    const vector<Fp> vfp6 {testFp2};
    const vector<Fp> vfp7 {testFp3};

    cout << "Test Methods..." << endl;

    // Test Methods
    // Centroid
    Point tric = centroid(tri);
    Point squarec = centroid(square);
    Point bigsc = centroid(bigSquare);
    cout << "Triangle" << tostr(tri) << tostr(tric) << endl;
    cout << "Square" << tostr(square) << tostr(squarec) << endl;
    cout << "Big Square" << tostr(bigSquare) << tostr(bigsc) << endl;
    cout << "Square & BigSquare Centroid: " << tostr(centroid(vpoly3)) << endl;

    // Dist & Angs
    vector<double> dts = dists(tri);
    vector<double> ans = angles(tri);
    cout << "Triangle lengths: " << vtostr(dts) << endl;
    cout << "Triangle angles: " << vtostr(ans) << endl;
    cout << "Unit Angle: " << "Origin - " << tostr(a) << "; Point - " << tostr(b) << "; Ang - " << angle(a,b) << endl;

    // All same length
    cout << "Triangle all same length? " << allSameLength(tri, (double)0.0) << endl;
    cout << "Square all same length? " << allSameLength(square, (double)0.0) << endl;

    // isPoly
    bool test1 = isPoly(tri, 3, false, false, 0, 0);  // True
    bool test2 = isPoly(tri, 3, true, true, 0, 0);  // False
    bool test3 = isPoly(tri, 4, false, false, 0, 0);  // False
    bool test4 = isRectangle(rect, false, 0, 0);  // True
    bool test5 = isRectangle(rect, true, 0, 0);  // False
    bool test6 = isSquare(square, 0, 0);  // True
    cout << test1 << test2 << test3 << test4 << test5 << test6 << endl;
}
Beispiel #12
0
int main(int argc, char* argv[])
{

    programname = copystring(Basename(argv[0]));

    argc--, argv++;
    while (argc && argv[0][0] == '-') {
        while (*++*argv)
            switch(**argv) {
	    case 'p':
                pflag++;
                break;
	    case 'e':
		eflag++;
                epsfwidth = WidthInPoints(*argv + 1);
                goto nextarg;
	    case 'd':
		dflag++;
                goto nextarg;
	    case 'i':
		switch( *(*argv + 1) ) {
		  case '-':
		    iflag = -1;
		  case '+':
		  default:
		    iflag = 1;
		}
                goto nextarg;
	    case 'g':
		gflag++;
		goto nextarg;
	    case 'y':
		yflag++;
		goto nextarg;
	    case 'b':
		bflag++;
		goto nextarg;
	    case 's':
		sflag++;
		goto nextarg;
	    case 'm':
		mflag++;
		TWENTY = atoi(*argv + 1);
		if (TWENTY > DEFAULT_TWENTY)
		    Usage(*argv-1);
		goto nextarg;
	    case 't':
		tflag++;
		THRESHOLD_PERCENT = (floatish) atof(*argv + 1);
		if (THRESHOLD_PERCENT < 0 || THRESHOLD_PERCENT > 5)
		    Usage(*argv-1);
		goto nextarg;
	    case 'c':
		cflag++;
		goto nextarg;
	    case '?':
	    default:
		Usage(*argv-1);
            }
nextarg: ;
        argc--, argv++;
    }

    hpfile = "stdin";
    psfile = "stdout";

    hpfp = stdin;
    psfp = stdout;

    filter = argc < 1;



    if (!filter) {
	pathName = copystring(argv[0]);
	DropSuffix(pathName, ".hp");
	baseName = copystring(Basename(pathName));

        hpfp  = Fp(pathName, &hpfile, ".hp", "r"); 

        // I changed these two lines to use 'pathName' instead of
        // 'baseName'.  This means that the .ps and .aux files get put in
        // the same directory as the .hp file.  This solved Valgrind bugt
        // #117686.  --njn 
//	psfp  = Fp(baseName, &psfile, ".ps", "w"); 
	psfp  = Fp(pathName, &psfile, ".ps", "w"); 

//	if (pflag) auxfp = Fp(baseName, &auxfile, ".aux", "r");
	if (pflag) auxfp = Fp(pathName, &auxfile, ".aux", "r");
    }

    GetHpFile(hpfp);

    if (!filter && pflag) GetAuxFile(auxfp);


    TraceElement();          /* Orders on total, Removes trace elements (tflag) */

    if (dflag) Deviation();  /* ReOrders on deviation */

    if (iflag) Identorder(iflag); /* ReOrders on identifier */

    if (pflag) Reorder();    /* ReOrders on aux file */

    if (TWENTY) TopTwenty(); /* Selects top twenty (mflag) */

    Dimensions();

    areabelow = AreaBelow();

    Scale();

    PutPsFile();

    if (!filter) {
        auxfp = Fp(baseName, &auxfile, ".aux", "w");
	PutAuxFile(auxfp);
    } 

    return(0);
}
// The matrix assembly function to be called at each time step to
// prepare for the linear solve.
void assemble_solid (EquationSystems& es,
                      const std::string& system_name)
{

//es.print_info();

#if LOG_ASSEMBLE_PERFORMANCE
  PerfLog perf_log("Assemble");
  perf_log.push("assemble stiffness");
#endif

    // Get a reference to the auxiliary system
  //TransientExplicitSystem& aux_system = es.get_system<TransientExplicitSystem>("Newton-update");

  // It is a good idea to make sure we are assembling
  // the proper system.
  libmesh_assert (system_name == "Newton-update");
  
  // Get a constant reference to the mesh object.
  const MeshBase& mesh = es.get_mesh();
  
  // The dimension that we are running
  const unsigned int dim = mesh.mesh_dimension();
  
  // Get a reference to the Stokes system object.
  TransientLinearImplicitSystem & newton_update =
   es.get_system<TransientLinearImplicitSystem> ("Newton-update");

  // New
   TransientLinearImplicitSystem & last_non_linear_soln =
    es.get_system<TransientLinearImplicitSystem> ("Last-non-linear-soln");

 TransientLinearImplicitSystem & fluid_system_vel =
    es.get_system<TransientLinearImplicitSystem> ("fluid-system-vel");

#if VELOCITY
TransientLinearImplicitSystem&  velocity = es.get_system<TransientLinearImplicitSystem>("velocity-system");
#endif

#if UN_MINUS_ONE
TransientLinearImplicitSystem & unm1 =
    es.get_system<TransientLinearImplicitSystem> ("unm1-system");
#endif
test(62);
const System & ref_sys = es.get_system("Reference-Configuration"); 
test(63);
  
  // Numeric ids corresponding to each variable in the system
  const unsigned int u_var = last_non_linear_soln .variable_number ("u");
  const unsigned int v_var = last_non_linear_soln .variable_number ("v");
  const unsigned int w_var = last_non_linear_soln .variable_number ("w");
#if INCOMPRESSIBLE
  const unsigned int p_var = last_non_linear_soln .variable_number ("p");
#endif 



#if FLUID_P_CONST
    const unsigned int m_var = fluid_system_vel.variable_number ("fluid_M");
  std::vector<unsigned int> dof_indices_m;
#endif


  // Get the Finite Element type for "u".  Note this will be
  // the same as the type for "v".
  FEType fe_vel_type = last_non_linear_soln.variable_type(u_var);


test(64);

#if INCOMPRESSIBLE
  // Get the Finite Element type for "p".
  FEType fe_pres_type = last_non_linear_soln .variable_type(p_var);
#endif 

  // Build a Finite Element object of the specified type for
  // the velocity variables.
  AutoPtr<FEBase> fe_vel  (FEBase::build(dim, fe_vel_type));
  
#if INCOMPRESSIBLE 
  // Build a Finite Element object of the specified type for
  // the pressure variables.
  AutoPtr<FEBase> fe_pres (FEBase::build(dim, fe_pres_type));
#endif 
  // A Gauss quadrature rule for numerical integration.
  // Let the \p FEType object decide what order rule is appropriate.
  QGauss qrule (dim, fe_vel_type.default_quadrature_order());

  // Tell the finite element objects to use our quadrature rule.
  fe_vel->attach_quadrature_rule (&qrule);
test(65);
//        AutoPtr<QBase> qrule2(fe_vel_type.default_quadrature_rule(dim));
// fe_vel->attach_quadrature_rule (qrule2.get());

#if INCOMPRESSIBLE 
  fe_pres->attach_quadrature_rule (&qrule);
#endif
  // The element Jacobian * quadrature weight at each integration point.   
  const std::vector<Real>& JxW = fe_vel->get_JxW();

  // The element shape functions evaluated at the quadrature points.
  const std::vector<std::vector<Real> >& phi = fe_vel->get_phi();

  // The element shape function gradients for the velocity
  // variables evaluated at the quadrature points.
  const std::vector<std::vector<RealGradient> >& dphi = fe_vel->get_dphi();
test(66);
#if INCOMPRESSIBLE 
  // The element shape functions for the pressure variable
  // evaluated at the quadrature points.
  const std::vector<std::vector<Real> >& psi = fe_pres->get_phi();
#endif
  
 const std::vector<Point>& coords = fe_vel->get_xyz();

  // A reference to the \p DofMap object for this system.  The \p DofMap
  // object handles the index translation from node and element numbers
  // to degree of freedom numbers.  We will talk more about the \p DofMap
  // in future examples.
  const DofMap & dof_map = last_non_linear_soln .get_dof_map();

#if FLUID_P_CONST 
  const DofMap & dof_map_fluid = fluid_system_vel .get_dof_map();
#endif

  // K will be the jacobian
  // F will be the Residual
  DenseMatrix<Number> Ke;
  DenseVector<Number> Fe;

  DenseSubMatrix<Number>
    Kuu(Ke), Kuv(Ke), Kuw(Ke),  
    Kvu(Ke), Kvv(Ke), Kvw(Ke),  
    Kwu(Ke), Kwv(Ke), Kww(Ke); 
    



#if INCOMPRESSIBLE
  DenseSubMatrix<Number>  Kup(Ke),Kvp(Ke),Kwp(Ke), Kpu(Ke), Kpv(Ke), Kpw(Ke), Kpp(Ke);
 #endif;
    
  DenseSubVector<Number>
    Fu(Fe), Fv(Fe), Fw(Fe);
#if INCOMPRESSIBLE
  DenseSubVector<Number>    Fp(Fe);
#endif
  // This vector will hold the degree of freedom indices for
  // the element.  These define where in the global system
  // the element degrees of freedom get mapped.
  std::vector<unsigned int> dof_indices;
  std::vector<unsigned int> dof_indices_u;
  std::vector<unsigned int> dof_indices_v;
  std::vector<unsigned int> dof_indices_w;
  
#if INCOMPRESSIBLE
  std::vector<unsigned int> dof_indices_p;
#endif
   

#if INERTIA
test(67);
  const unsigned int a_var = last_non_linear_soln.variable_number ("a");
  const unsigned int b_var = last_non_linear_soln.variable_number ("b");
  const unsigned int c_var = last_non_linear_soln.variable_number ("c");

//B block
  DenseSubMatrix<Number>
  Kua(Ke), Kub(Ke), Kuc(Ke),
  Kva(Ke), Kvb(Ke), Kvc(Ke),
  Kwa(Ke), Kwb(Ke), Kwc(Ke); 

//C block
  DenseSubMatrix<Number>
  Kau(Ke), Kav(Ke), Kaw(Ke),
  Kbu(Ke), Kbv(Ke), Kbw(Ke),
  Kcu(Ke), Kcv(Ke), Kcw(Ke);

//D block
  DenseSubMatrix<Number>
  Kaa(Ke), Kab(Ke), Kac(Ke),
  Kba(Ke), Kbb(Ke), Kbc(Ke),
  Kca(Ke), Kcb(Ke), Kcc(Ke);

  DenseSubVector<Number>
  Fa(Fe), Fb(Fe), Fc(Fe);

  std::vector<unsigned int> dof_indices_a;
  std::vector<unsigned int> dof_indices_b;
  std::vector<unsigned int> dof_indices_c;
test(68);
#endif

    DenseMatrix<Real> stiff;
  DenseVector<Real> res;
  VectorValue<Gradient> grad_u_mat;

  VectorValue<Gradient> grad_u_mat_old;
    const Real dt    = es.parameters.get<Real>("dt");
    const Real progress    = es.parameters.get<Real>("progress");


#if PORO 
  DenseVector<Real> p_stiff;
  DenseVector<Real> p_res;
  PoroelasticConfig material(dphi,psi);
#endif

  // Just calculate jacobian contribution when we need to
  material.calculate_linearized_stiffness = true;
  MeshBase::const_element_iterator       el     = mesh.active_local_elements_begin();
  const MeshBase::const_element_iterator end_el = mesh.active_local_elements_end(); 

  for ( ; el != end_el; ++el)
    {  
test(69);  
      const Elem* elem = *el;
      
      dof_map.dof_indices (elem, dof_indices);
      dof_map.dof_indices (elem, dof_indices_u, u_var);
      dof_map.dof_indices (elem, dof_indices_v, v_var);
      dof_map.dof_indices (elem, dof_indices_w, w_var);
#if INCOMPRESSIBLE
      dof_map.dof_indices (elem, dof_indices_p, p_var);
#endif
      const unsigned int n_dofs   = dof_indices.size();
      const unsigned int n_u_dofs = dof_indices_u.size(); 
      const unsigned int n_v_dofs = dof_indices_v.size(); 
      const unsigned int n_w_dofs = dof_indices_w.size(); 
#if INCOMPRESSIBLE
      const unsigned int n_p_dofs = dof_indices_p.size();
#endif

#if FLUID_P_CONST
      dof_map_fluid.dof_indices (elem, dof_indices_m, m_var);
#endif
      //elem->print_info();

      fe_vel->reinit  (elem);

#if INCOMPRESSIBLE
      fe_pres->reinit (elem);
#endif

      Ke.resize (n_dofs, n_dofs);
      Fe.resize (n_dofs);

      Kuu.reposition (u_var*n_u_dofs, u_var*n_u_dofs, n_u_dofs, n_u_dofs);
      Kuv.reposition (u_var*n_u_dofs, v_var*n_u_dofs, n_u_dofs, n_v_dofs);
      Kuw.reposition (u_var*n_u_dofs, w_var*n_u_dofs, n_u_dofs, n_w_dofs);
      #if INCOMPRESSIBLE
      Kup.reposition (u_var*n_u_dofs, p_var*n_u_dofs, n_u_dofs, n_p_dofs);
      #endif
      Kvu.reposition (v_var*n_v_dofs, u_var*n_v_dofs, n_v_dofs, n_u_dofs);
      Kvv.reposition (v_var*n_v_dofs, v_var*n_v_dofs, n_v_dofs, n_v_dofs);
      Kvw.reposition (v_var*n_v_dofs, w_var*n_v_dofs, n_v_dofs, n_w_dofs);
      #if INCOMPRESSIBLE
      Kvp.reposition (v_var*n_v_dofs, p_var*n_v_dofs, n_v_dofs, n_p_dofs);
      #endif
      
      Kwu.reposition (w_var*n_w_dofs, u_var*n_w_dofs, n_w_dofs, n_u_dofs);
      Kwv.reposition (w_var*n_w_dofs, v_var*n_w_dofs, n_w_dofs, n_v_dofs);
      Kww.reposition (w_var*n_w_dofs, w_var*n_w_dofs, n_w_dofs, n_w_dofs);
      #if INCOMPRESSIBLE
      Kwp.reposition (w_var*n_w_dofs, p_var*n_w_dofs, n_w_dofs, n_p_dofs);
      Kpu.reposition (p_var*n_u_dofs, u_var*n_u_dofs, n_p_dofs, n_u_dofs);
      Kpv.reposition (p_var*n_u_dofs, v_var*n_u_dofs, n_p_dofs, n_v_dofs);
      Kpw.reposition (p_var*n_u_dofs, w_var*n_u_dofs, n_p_dofs, n_w_dofs);
      Kpp.reposition (p_var*n_u_dofs, p_var*n_u_dofs, n_p_dofs, n_p_dofs);
      #endif



      
      Fu.reposition (u_var*n_u_dofs, n_u_dofs);
      Fv.reposition (v_var*n_u_dofs, n_v_dofs);
      Fw.reposition (w_var*n_u_dofs, n_w_dofs);
      #if INCOMPRESSIBLE
      Fp.reposition (p_var*n_u_dofs, n_p_dofs);
      #endif




#if INERTIA

//B block
   Kua.reposition (u_var*n_u_dofs, 3*n_u_dofs + n_p_dofs, n_u_dofs, n_u_dofs);
   Kub.reposition (u_var*n_u_dofs, 4*n_u_dofs + n_p_dofs, n_u_dofs, n_v_dofs);
   Kuc.reposition (u_var*n_u_dofs, 5*n_u_dofs + n_p_dofs, n_u_dofs, n_w_dofs);
   Kva.reposition (v_var*n_v_dofs, 3*n_u_dofs + n_p_dofs, n_v_dofs, n_u_dofs);
   Kvb.reposition (v_var*n_v_dofs, 4*n_u_dofs + n_p_dofs, n_v_dofs, n_v_dofs);
   Kvc.reposition (v_var*n_v_dofs, 5*n_u_dofs + n_p_dofs, n_v_dofs, n_w_dofs);
   Kwa.reposition (w_var*n_w_dofs, 3*n_u_dofs + n_p_dofs, n_w_dofs, n_u_dofs);
   Kwb.reposition (w_var*n_w_dofs, 4*n_u_dofs + n_p_dofs, n_w_dofs, n_v_dofs);
   Kwc.reposition (w_var*n_w_dofs, 5*n_u_dofs + n_p_dofs, n_w_dofs, n_w_dofs);

test(701);  
//C block
   Kau.reposition (3*n_u_dofs + n_p_dofs, u_var*n_u_dofs, n_u_dofs, n_u_dofs);
   Kav.reposition (3*n_u_dofs + n_p_dofs, v_var*n_u_dofs, n_u_dofs, n_v_dofs);
   Kaw.reposition (3*n_u_dofs + n_p_dofs, w_var*n_u_dofs, n_u_dofs, n_w_dofs);
   Kbu.reposition (4*n_u_dofs + n_p_dofs, u_var*n_v_dofs, n_v_dofs, n_u_dofs);
   Kbv.reposition (4*n_u_dofs + n_p_dofs, v_var*n_v_dofs, n_v_dofs, n_v_dofs);
   Kbw.reposition (4*n_u_dofs + n_p_dofs, w_var*n_v_dofs, n_v_dofs, n_w_dofs);
   Kcu.reposition (5*n_u_dofs + n_p_dofs, u_var*n_w_dofs, n_w_dofs, n_u_dofs);
   Kcv.reposition (5*n_u_dofs + n_p_dofs, v_var*n_w_dofs, n_w_dofs, n_v_dofs);
   Kcw.reposition (5*n_u_dofs + n_p_dofs, w_var*n_w_dofs, n_w_dofs, n_w_dofs);

//D block
   Kaa.reposition (3*n_u_dofs + n_p_dofs, 3*n_u_dofs + n_p_dofs, n_u_dofs, n_u_dofs);
   Kab.reposition (3*n_u_dofs + n_p_dofs, 4*n_u_dofs + n_p_dofs, n_u_dofs, n_v_dofs);
   Kac.reposition (3*n_u_dofs + n_p_dofs, 5*n_u_dofs + n_p_dofs, n_u_dofs, n_w_dofs);
   Kba.reposition (4*n_u_dofs + n_p_dofs, 3*n_u_dofs + n_p_dofs, n_v_dofs, n_u_dofs);
   Kbb.reposition (4*n_u_dofs + n_p_dofs, 4*n_u_dofs + n_p_dofs, n_v_dofs, n_v_dofs);
   Kbc.reposition (4*n_u_dofs + n_p_dofs, 5*n_u_dofs + n_p_dofs, n_v_dofs, n_w_dofs);
   Kca.reposition (5*n_u_dofs + n_p_dofs, 3*n_u_dofs + n_p_dofs, n_w_dofs, n_u_dofs);
   Kcb.reposition (5*n_u_dofs + n_p_dofs, 4*n_u_dofs + n_p_dofs, n_w_dofs, n_v_dofs);
   Kcc.reposition (5*n_u_dofs + n_p_dofs, 5*n_u_dofs + n_p_dofs, n_w_dofs, n_w_dofs);


Fa.reposition (3*n_u_dofs + n_p_dofs, n_u_dofs);
Fb.reposition (4*n_u_dofs + n_p_dofs, n_v_dofs);
Fc.reposition (5*n_u_dofs + n_p_dofs, n_w_dofs);

  dof_map.dof_indices (elem, dof_indices_a, a_var);
  dof_map.dof_indices (elem, dof_indices_b, b_var);
  dof_map.dof_indices (elem, dof_indices_c, c_var);

test(71);  
#endif


      System& aux_system = es.get_system<System>("Reference-Configuration");
      std::vector<unsigned int> undefo_index;
      std::vector<unsigned int> vel_index;           

      for (unsigned int qp=0; qp<qrule.n_points(); qp++)
        {



 Point rX;
 for (unsigned int l=0; l<n_u_dofs; l++)
            {
rX(0) += phi[l][qp]*ref_sys.current_local_solution->el(dof_indices_u[l]);
rX(1) += phi[l][qp]*ref_sys.current_local_solution->el(dof_indices_v[l]);
rX(2) += phi[l][qp]*ref_sys.current_local_solution->el(dof_indices_w[l]);
            }



#if INERTIA || DT
test(72);  
Real rho_s=15;

Point current_x;
 for (unsigned int l=0; l<n_u_dofs; l++)
 {
current_x(0) += phi[l][qp]*last_non_linear_soln.current_local_solution->el(dof_indices_u[l]);
current_x(1) += phi[l][qp]*last_non_linear_soln.current_local_solution->el(dof_indices_v[l]);
current_x(2) += phi[l][qp]*last_non_linear_soln.current_local_solution->el(dof_indices_w[l]);
}

Point old_x;
 for (unsigned int l=0; l<n_u_dofs; l++)
 {
old_x(0) += phi[l][qp]*last_non_linear_soln.old_local_solution->el(dof_indices_u[l]);
old_x(1) += phi[l][qp]*last_non_linear_soln.old_local_solution->el(dof_indices_v[l]);
old_x(2) += phi[l][qp]*last_non_linear_soln.old_local_solution->el(dof_indices_w[l]);
}
#if INERTIA
Point old_vel;
 for (unsigned int l=0; l<n_u_dofs; l++)
 {
old_vel(0) += phi[l][qp]*last_non_linear_soln.old_local_solution->el(dof_indices_a[l]);
old_vel(1) += phi[l][qp]*last_non_linear_soln.old_local_solution->el(dof_indices_b[l]);
old_vel(2) += phi[l][qp]*last_non_linear_soln.old_local_solution->el(dof_indices_c[l]);
}
Point current_vel;
 for (unsigned int l=0; l<n_u_dofs; l++)
 {
current_vel(0) += phi[l][qp]*last_non_linear_soln.current_local_solution->el(dof_indices_a[l]);
current_vel(1) += phi[l][qp]*last_non_linear_soln.current_local_solution->el(dof_indices_b[l]);
current_vel(2) += phi[l][qp]*last_non_linear_soln.current_local_solution->el(dof_indices_c[l]);
}
#endif

#if UN_MINUS_ONE
Point unm1_x;
 for (unsigned int l=0; l<n_u_dofs; l++)
 {
unm1_x(0) += phi[l][qp]*unm1.old_local_solution->el(dof_indices_u[l]);
unm1_x(1) += phi[l][qp]*unm1.old_local_solution->el(dof_indices_v[l]);
unm1_x(2) += phi[l][qp]*unm1.old_local_solution->el(dof_indices_w[l]);
}
#endif

Point value_acc;
Point value_acc_alt;

#if DT
for (unsigned int d = 0; d < dim; ++d) {
 value_acc_alt(d) = (rho_s)*( ((current_x(d)-rX(d))-(old_x(d)-rX(d)))-((old_x(d)-rX(d))- (unm1_x(d)-rX(d))) );  
value_acc(d) = (rho_s)*((current_x(d))-2*(old_x(d))+ (unm1_x(d)));  
value_acc(d) = (rho_s)*((current_x(d))-(old_x(d)));  
}
#endif

Point res_1;
Point res_2;
#if INERTIA
for (unsigned int d = 0; d < dim; ++d) {
res_1(d) = (rho_s)*((current_vel(d))-(old_vel(d)));
res_2(d) = current_x(d)-dt*current_vel(d)-old_x(d);    
}
/*
std::cout<<" current_vel "<<current_vel<<std::endl;
std::cout<<" res_1 "<<res_1<<std::endl;
std::cout<<" res_2 "<<res_2<<std::endl;
*/
#endif



test(73);  
#endif


Number   p_solid = 0.;

#if MOVING_MESH
	grad_u_mat(0) = grad_u_mat(1) = grad_u_mat(2) = 0;
    for (unsigned int d = 0; d < dim; ++d) {
      std::vector<Number> u_undefo;
//Fills the vector di with the global degree of freedom indices for the element. :dof_indicies
      aux_system.get_dof_map().dof_indices(elem, undefo_index,d);
      aux_system.current_local_solution->get(undefo_index, u_undefo);
      for (unsigned int l = 0; l != n_u_dofs; l++)
        grad_u_mat(d).add_scaled(dphi[l][qp], u_undefo[l]); 
 }
#endif


//#include "fixed_mesh_in_solid_assemble_code.txt"
          
      #if INCOMPRESSIBLE
      for (unsigned int l=0; l<n_p_dofs; l++)
            {
              p_solid += psi[l][qp]*last_non_linear_soln.current_local_solution->el(dof_indices_p[l]);
            }
      #endif
	  


#if INCOMPRESSIBLE 
Real m=0;
Real p_fluid=0;

#if FLUID_VEL 
for (unsigned int l=0; l<n_p_dofs; l++)
 {
   p_fluid += psi[l][qp]*fluid_system_vel.current_local_solution->el(dof_indices_p[l]);
 }

//As outlined in Chappel p=(p_curr-p_old)/2
 Real p_fluid_old=0;
for (unsigned int l=0; l<n_p_dofs; l++)
 {
   p_fluid_old += psi[l][qp]*fluid_system_vel.old_local_solution->el(dof_indices_p[l]);
 }
p_fluid=0.5*p_fluid+0.5*p_fluid_old;


Real m_old=0;

#if FLUID_P_CONST
for (unsigned int l=0; l<n_p_dofs; l++)
 {
   m += psi[l][qp]*fluid_system_vel.current_local_solution->el(dof_indices_m[l]);
 }


for (unsigned int l=0; l<n_p_dofs; l++)
 {
   m_old += psi[l][qp]*fluid_system_vel.old_local_solution->el(dof_indices_m[l]);
 }
#endif

material.init_for_qp(grad_u_mat, p_solid, qp, 1.0*m+0.0*m_old, p_fluid);

#endif
#endif //#if INCOMPRESSIBLE


#if INCOMPRESSIBLE && ! PORO
material.init_for_qp(grad_u_mat, p_solid, qp);
#endif 

          for (unsigned int i=0; i<n_u_dofs; i++)
            {
            res.resize(dim);
            material.get_residual(res, i);
            res.scale(JxW[qp]);
#if INERTIA
            res.scale(dt);
#endif

#if DT
            res.scale(dt);
#endif
//std::cout<< "res "<<res<<std::endl;

      	    Fu(i) += res(0);              
            Fv(i) += res(1) ; 
	    Fw(i) += res(2);  

  	#if GRAVITY
        Real grav=0.0;
        Fu(i) += progress*grav*JxW[qp]*phi[i][qp];
	#endif

#if INERTIA
      Fu(i) +=  JxW[qp]*phi[i][qp]*res_1(0); 
      Fv(i) +=  JxW[qp]*phi[i][qp]*res_1(1);     
      Fw(i) +=  JxW[qp]*phi[i][qp]*res_1(2); 

      Fa(i) +=  JxW[qp]*phi[i][qp]*res_2(0);  
      Fb(i) +=  JxW[qp]*phi[i][qp]*res_2(1);      
      Fc(i) +=  JxW[qp]*phi[i][qp]*res_2(2);  
#endif


// Matrix contributions for the uu and vv couplings.
for (unsigned int j=0; j<n_u_dofs; j++)
   {
    material.get_linearized_stiffness(stiff, i, j);
    stiff.scale(JxW[qp]);

#if DT
            res.scale(dt);
#endif

#if INERTIA 
    stiff.scale(dt);
    Kua(i,j)+=  rho_s*JxW[qp]*phi[i][qp]*phi[j][qp];      
    Kvb(i,j)+=  rho_s*JxW[qp]*phi[i][qp]*phi[j][qp];
    Kwc(i,j)+=  rho_s*JxW[qp]*phi[i][qp]*phi[j][qp];


    Kau(i,j)+=  JxW[qp]*phi[i][qp]*phi[j][qp];      
    Kbv(i,j)+=  JxW[qp]*phi[i][qp]*phi[j][qp];
    Kcw(i,j)+=  JxW[qp]*phi[i][qp]*phi[j][qp];

    Kaa(i,j)+=  -dt*JxW[qp]*phi[i][qp]*phi[j][qp];      
    Kbb(i,j)+=  -dt*JxW[qp]*phi[i][qp]*phi[j][qp];
    Kcc(i,j)+=  -dt*JxW[qp]*phi[i][qp]*phi[j][qp];
#endif




    Kuu(i,j)+=  stiff(u_var, u_var);
    Kuv(i,j)+=  stiff(u_var, v_var);
    Kuw(i,j)+=  stiff(u_var, w_var);	      
    Kvu(i,j)+=  stiff(v_var, u_var);
    Kvv(i,j)+=  stiff(v_var, v_var);
    Kvw(i,j)+=  stiff(v_var, w_var);
    Kwu(i,j)+=  stiff(w_var, u_var);
    Kwv(i,j)+=  stiff(w_var, v_var);
    Kww(i,j)+=  stiff(w_var, w_var); 


#if GRAVITY
    Kuu(i,j)+= 1*JxW[qp]*phi[i][qp]*phi[j][qp];
#endif
                }
            }


#if INCOMPRESSIBLE && FLUID_P_CONST
         for (unsigned int i = 0; i < n_p_dofs; i++) {
	  material.get_p_residual(p_res, i);
	  p_res.scale(JxW[qp]);
          Fp(i) += p_res(0);
	  }
    
    for (unsigned int i = 0; i < n_u_dofs; i++) {
          for (unsigned int j = 0; j < n_p_dofs; j++) {
	    material.get_linearized_uvw_p_stiffness(p_stiff, i, j);
	   p_stiff.scale(JxW[qp]);
            Kup(i, j) += p_stiff(0);
	    Kvp(i, j) += p_stiff(1);
            Kwp(i, j) += p_stiff(2);
	  }
    }
    
    for (unsigned int i = 0; i < n_p_dofs; i++) {
          for (unsigned int j = 0; j < n_u_dofs; j++) {
	    material.get_linearized_p_uvw_stiffness(p_stiff, i, j);
	    p_stiff.scale(JxW[qp]);
      Kpu(i, j) += p_stiff(0);
	    Kpv(i, j) += p_stiff(1);
      Kpw(i, j) += p_stiff(2);
       }
    }
#endif

#if CHAP && ! FLUID_P_CONST
           for (unsigned int i = 0; i < n_p_dofs; i++) {
         Fp(i) += 0*JxW[qp]*psi[i][qp];
    }
    
    for (unsigned int i = 0; i < n_p_dofs; i++) {
          for (unsigned int j = 0; j < n_p_dofs; j++) {
            Kpp(i, j) += 1*JxW[qp]*psi[i][qp]*psi[j][qp];
    }
    }
#endif



}//end of qp loop

      newton_update.matrix->add_matrix (Ke, dof_indices);
      newton_update.rhs->add_vector    (Fe, dof_indices);
} // end of element loop

     //   dof_map.constrain_element_matrix_and_vector (Ke, Fe, dof_indices);
     newton_update.rhs->close();
     newton_update.matrix->close();

#if LOG_ASSEMBLE_PERFORMANCE
perf_log.pop("assemble stiffness");
#endif 

#if LOG_ASSEMBLE_PERFORMANCE
perf_log.push("assemble bcs");
#endif

//Assemble the boundary conditions.
assemble_bcs(es);

#if LOG_ASSEMBLE_PERFORMANCE
perf_log.pop("assemble bcs");
#endif

std::ofstream lhs_out("lhsoutS3.dat");
Ke.print(lhs_out);
lhs_out.close();
  return;
}
void BoussinesqBuoyancyAdjointStabilization<Mu>::element_constraint( bool compute_jacobian,
        AssemblyContext& context,
        CachedValues& /*cache*/ )
{
#ifdef GRINS_USE_GRVY_TIMERS
    this->_timer->BeginTimer("BoussinesqBuoyancyAdjointStabilization::element_constraint");
#endif

    // The number of local degrees of freedom in each variable.
    const unsigned int n_p_dofs = context.get_dof_indices(_flow_vars.p_var()).size();
    const unsigned int n_u_dofs = context.get_dof_indices(_flow_vars.u_var()).size();
    const unsigned int n_T_dofs = context.get_dof_indices(_temp_vars.T_var()).size();

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

    const std::vector<std::vector<libMesh::Real> >& T_phi =
        context.get_element_fe(this->_temp_vars.T_var())->get_phi();

    const std::vector<std::vector<libMesh::Real> >& u_phi =
        context.get_element_fe(this->_flow_vars.u_var())->get_phi();

    const std::vector<std::vector<libMesh::RealGradient> >& p_dphi =
        context.get_element_fe(this->_flow_vars.p_var())->get_dphi();

    libMesh::DenseSubVector<libMesh::Number> &Fp = context.get_elem_residual(this->_flow_vars.p_var()); // R_{p}

    libMesh::DenseSubMatrix<libMesh::Number> &KpT =
        context.get_elem_jacobian(_flow_vars.p_var(), _temp_vars.T_var()); // J_{pT}
    libMesh::DenseSubMatrix<libMesh::Number> &Kpu =
        context.get_elem_jacobian(_flow_vars.p_var(), _flow_vars.u_var()); // J_{pu}
    libMesh::DenseSubMatrix<libMesh::Number> &Kpv =
        context.get_elem_jacobian(_flow_vars.p_var(), _flow_vars.v_var()); // J_{pv}
    libMesh::DenseSubMatrix<libMesh::Number> *Kpw = NULL;

    if(this->_dim == 3)
    {
        Kpw = &context.get_elem_jacobian
              (_flow_vars.p_var(), _flow_vars.w_var()); // J_{pw}
    }

    // 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();

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

    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_var(), qp ),
                                 context.interior_value( this->_flow_vars.v_var(), qp ) );
        if( this->_dim == 3 )
        {
            U(2) = context.interior_value( this->_flow_vars.w_var(), qp );
        }

        // Compute the viscosity at this qp
        libMesh::Real mu_qp = this->_mu(context, qp);

        libMesh::Real tau_M;
        libMesh::Real d_tau_M_d_rho;
        libMesh::Gradient d_tau_M_dU;

        if (compute_jacobian)
            this->_stab_helper.compute_tau_momentum_and_derivs
            ( context, qp, g, G, this->_rho, U, mu_qp,
              tau_M, d_tau_M_d_rho, d_tau_M_dU,
              this->_is_steady );
        else
            tau_M = this->_stab_helper.compute_tau_momentum
                    ( context, qp, g, G, this->_rho, U, mu_qp,
                      this->_is_steady );

        // Compute the solution & its gradient at the old Newton iterate.
        libMesh::Number T;
        T = context.interior_value(_temp_vars.T_var(), qp);

        libMesh::RealGradient d_residual_dT = _rho_ref*_beta_T*_g;
        // d_residual_dU = 0
        libMesh::RealGradient residual = (T-_T_ref)*d_residual_dT;

        // First, an i-loop over the velocity degrees of freedom.
        // We know that n_u_dofs == n_v_dofs so we can compute contributions
        // for both at the same time.
        for (unsigned int i=0; i != n_p_dofs; i++)
        {
            Fp(i) += tau_M*residual*p_dphi[i][qp]*JxW[qp];

            if (compute_jacobian)
            {
                for (unsigned int j=0; j != n_T_dofs; ++j)
                {
                    KpT(i,j) += tau_M*d_residual_dT*T_phi[j][qp]*p_dphi[i][qp]*JxW[qp] * context.get_elem_solution_derivative();
                }

                for (unsigned int j=0; j != n_u_dofs; ++j)
                {
                    Kpu(i,j) += d_tau_M_dU(0)*u_phi[j][qp]*residual*p_dphi[i][qp]*JxW[qp] * context.get_elem_solution_derivative();
                    Kpv(i,j) += d_tau_M_dU(1)*u_phi[j][qp]*residual*p_dphi[i][qp]*JxW[qp] * context.get_elem_solution_derivative();
                }
                if( this->_dim == 3 )
                    for (unsigned int j=0; j != n_u_dofs; ++j)
                    {
                        (*Kpw)(i,j) += d_tau_M_dU(2)*u_phi[j][qp]*residual*p_dphi[i][qp]*JxW[qp] * context.get_elem_solution_derivative();
                    }
            }
        }
    } // End quadrature loop

#ifdef GRINS_USE_GRVY_TIMERS
    this->_timer->EndTimer("BoussinesqBuoyancyAdjointStabilization::element_constraint");
#endif

    return;
}
void DislocationDensity<EvalT, Traits>::
evaluateFields(typename Traits::EvalData workset)
{

  Teuchos::SerialDenseMatrix<int, double> A;
  Teuchos::SerialDenseMatrix<int, double> X;
  Teuchos::SerialDenseMatrix<int, double> B;
  Teuchos::SerialDenseSolver<int, double> solver;

  A.shape(numNodes,numNodes);
  X.shape(numNodes,numNodes);
  B.shape(numNodes,numNodes);
  
  // construct Identity for RHS
  for (int i = 0; i < numNodes; ++i)
    B(i,i) = 1.0;

  for (int i=0; i < G.size() ; i++) G[i] = 0.0;

  // construct the node --> point operator
  for (std::size_t cell=0; cell < workset.numCells; ++cell)
  {
    for (std::size_t node=0; node < numNodes; ++node) 
      for (std::size_t qp=0; qp < numQPs; ++qp) 
	A(qp,node) = BF(cell,node,qp);
    
    X = 0.0;

    solver.setMatrix( Teuchos::rcp( &A, false) );
    solver.setVectors( Teuchos::rcp( &X, false ), Teuchos::rcp( &B, false ) );

    // Solve the system A X = B to find A_inverse
    int status = 0;
    status = solver.factor();
    status = solver.solve();

    // compute nodal Fp
    nodalFp.initialize(0.0);
    for (std::size_t node=0; node < numNodes; ++node) 
      for (std::size_t qp=0; qp < numQPs; ++qp) 
	for (std::size_t i=0; i < numDims; ++i) 
	  for (std::size_t j=0; j < numDims; ++j) 
	    nodalFp(node,i,j) += X(node,qp) * Fp(cell,qp,i,j);

    // compute the curl using nodalFp
    curlFp.initialize(0.0);
    for (std::size_t node=0; node < numNodes; ++node) 
    {
      for (std::size_t qp=0; qp < numQPs; ++qp) 
      {
	curlFp(qp,0,0) += nodalFp(node,0,2) * GradBF(cell,node,qp,1) - nodalFp(node,0,1) * GradBF(cell,node,qp,2);
	curlFp(qp,0,1) += nodalFp(node,1,2) * GradBF(cell,node,qp,1) - nodalFp(node,1,1) * GradBF(cell,node,qp,2);
	curlFp(qp,0,2) += nodalFp(node,2,2) * GradBF(cell,node,qp,1) - nodalFp(node,2,1) * GradBF(cell,node,qp,2);

	curlFp(qp,1,0) += nodalFp(node,0,0) * GradBF(cell,node,qp,2) - nodalFp(node,0,2) * GradBF(cell,node,qp,0);
	curlFp(qp,1,1) += nodalFp(node,1,0) * GradBF(cell,node,qp,2) - nodalFp(node,1,2) * GradBF(cell,node,qp,0);
	curlFp(qp,1,2) += nodalFp(node,2,0) * GradBF(cell,node,qp,2) - nodalFp(node,2,2) * GradBF(cell,node,qp,0);

	curlFp(qp,2,0) += nodalFp(node,0,1) * GradBF(cell,node,qp,0) - nodalFp(node,0,0) * GradBF(cell,node,qp,1);
	curlFp(qp,2,1) += nodalFp(node,1,1) * GradBF(cell,node,qp,0) - nodalFp(node,1,0) * GradBF(cell,node,qp,1);
	curlFp(qp,2,2) += nodalFp(node,2,1) * GradBF(cell,node,qp,0) - nodalFp(node,2,0) * GradBF(cell,node,qp,1);
      }
    }

    for (std::size_t qp=0; qp < numQPs; ++qp) 
      for (std::size_t i=0; i < numDims; ++i) 
	for (std::size_t j=0; j < numDims; ++j) 
	  for (std::size_t k=0; k < numDims; ++k) 
	    G(cell,qp,i,j) += Fp(cell,qp,i,k) * curlFp(qp,k,j);
  }
}
Beispiel #16
0
int main()
{
	SystemInit();
	const Ec1 g1(-1, 1);
	const Ec2 g2(
		Fp2(Fp(g2c.aa), Fp(g2c.ab)),
		Fp2(Fp(g2c.ba), Fp(g2c.bb))
	);
	// assertBool g2 and g1 on curve
	assertBool("g1 is on EC", g1.isValid());
	assertBool("g2 is on twist EC", g2.isValid());
	puts("order of group");
	const Mpz& r = GetParamR();
	PUT(r);
	{
		Ec1 t = g1;
		t.mul(r);
		assertBool("orgder of g1 == r", t.isZero());
	}
	{
		Ec2 t = g2;
		t.mul(r);
		assertBool("order of g2 == r", t.isZero());
	}
	const Mpz a("123456789012345");
	const Mpz b("998752342342342342424242421");

	// scalar-multiplication sample
	{
		Mpz c = a;
		c.add(b);
		Ec1 Pa = g1; Pa.mul(a);
		Ec1 Pb = g1; Pb.mul(b);
		Ec1 Pc = g1; Pc.mul(c);
		Ec1 out = Pa;
		out.add(Pb);

		assertEqual("check g1 * c = g1 * a + g1 * b", Pc, out);
	}

	Fp12 e;
	// calc e : G2 x G1 -> G3 pairing
	e.pairing(g2, g1); // e = e(g2, g1)
	PUT(e);
	{
		Fp12 t = e;
		t.power(r);
		assertEqual("order of e == r", t, Fp12(1));
	}
	Ec2 g2a = g2;
	g2a.mul(a);
	Fp12 ea1;
	ea1.pairing(g2a, g1);
	Fp12 ea2 = e;
	ea2.power(a); // ea2 = e^a
	assertEqual("e(g2 * a, g1) = e(g2, g1)^a", ea1, ea2);

	Ec1 g1b = g1;
	g1b.mul(b);
	Fp12 eb1;
	eb1.pairing(g2, g1b); // eb1 = e(g2, g1b)
	Fp12 eb2 = e;
	eb2.power(b); // eb2 = e^b
	assertEqual("e(g2a, g1 * b) = e(g2, g1)^b", eb1, eb2);

	Ec1 q1 = g1;
	q1.mul(12345);
	assertBool("q1 is on EC", q1.isValid());
	Fp12 e1, e2;
	e1.pairing(g2, g1); // e1 = e(g2, g1)
	e2.pairing(g2, q1); // e2 = e(g2, q1)
	Ec1 q2 = g1;
	q2.add(q1);
	e.pairing(g2, q2); // e = e(g2, q2)
	e1.mul(e2);
	assertEqual("e = e1 * e2", e, e1);
	/*
		reduce one copy as the following
	*/
	g2a = g2;
	g2a.mul(a);
	g1b = g1;
	g1b.mul(b);
	Ec2 g2at = g2; g2at.mul(a);
	Ec1 g1bt = g1; g1bt.mul(b);
	assertEqual("g2a == g2 * a", g2a, g2at);
	assertEqual("g1b == g1 * b", g1b, g1bt);
	printf("errNum = %d\n", errNum);
}
Beispiel #17
0
Fp PublicParams::getFp(long x) const {
    return Fp(x);
}
Fp operator+(const Fp& me, const Fp& rhs) {
  return Fp(me.x + rhs.x);
}
Beispiel #19
0
int main(int argc, char *argv[])
{

    programname = copystring(Basename(argv[0]));

    argc--, argv++;
    while (argc && argv[0][0] == '-') {
        while (*++*argv)
            switch(**argv) {
	    case 'p':
                pflag++;
                break;
	    case 'e':
		eflag++;
                epsfwidth = WidthInPoints(*argv + 1);
                goto nextarg;
	    case 'd':
		dflag++;
                goto nextarg;
	    case 'i':
		switch( *(*argv + 1) ) {
		  case '-':
		    iflag = -1;
		    break;
		  case '+':
		  default:
		    iflag = 1;
		}
                goto nextarg;
	    case 'g':
		gflag++;
		goto nextarg;
	    case 'y':
		yflag++;
		goto nextarg;
	    case 'b':
		bflag++;
		goto nextarg;
	    case 's':
		sflag++;
		goto nextarg;
	    case 'm':
		mflag++;
		TWENTY = atoi(*argv + 1);
		// only 20 keys fit on a page
		if (TWENTY > DEFAULT_TWENTY) 
		   multipageflag++;
		goto nextarg;
	    case 'M':
	        multipageflag++;
                goto nextarg;
	    case 't':
		tflag++;
		THRESHOLD_PERCENT = (floatish) atof(*argv + 1);
		if (THRESHOLD_PERCENT < 0 || THRESHOLD_PERCENT > 5)
		    Usage(*argv-1);
		goto nextarg;
	    case 'c':
		cflag++;
		goto nextarg;
	    case '?':
	    default:
		Usage(*argv-1);
            }
nextarg: ;
        argc--, argv++;
    }

    hpfile = "stdin";
    psfile = "stdout";

    hpfp = stdin;
    psfp = stdout;

    filter = argc < 1;



    if (!filter) {
	pathName = copystring(argv[0]);
	DropSuffix(pathName, ".hp");
#if defined(_WIN32)
	DropSuffix(pathName, ".exe");
#endif
	baseName = copystring(Basename(pathName));
        
        hpfp  = Fp(pathName, &hpfile, ".hp", "r"); 
	psfp  = Fp(baseName, &psfile, ".ps", "w"); 

	if (pflag) auxfp = Fp(baseName, &auxfile, ".aux", "r");
    }

    GetHpFile(hpfp);

    if (!filter && pflag) GetAuxFile(auxfp);


    TraceElement();          /* Orders on total, Removes trace elements (tflag) */

    if (dflag) Deviation();  /* ReOrders on deviation */

    if (iflag) Identorder(iflag); /* ReOrders on identifier */

    if (pflag) Reorder();    /* ReOrders on aux file */

    /* Selects top bands (mflag) - can be more than 20 now */
    if (TWENTY != 0) TopTwenty(); 

    Dimensions();

    areabelow = AreaBelow();

    Scale();

    PutPsFile();

    if (!filter) {
        auxfp = Fp(baseName, &auxfile, ".aux", "w");
	PutAuxFile(auxfp);
    } 

    return(0);
}