Пример #1
0
PetscErrorCode ComputeRHS(KSP ksp,Vec b,void *ctx)
{
  PetscErrorCode ierr;
  PetscInt       mx;
  PetscScalar    h;
  Vec            x;
  DM             da;

  PetscFunctionBeginUser;
  ierr = KSPGetDM(ksp,&da);CHKERRQ(ierr);
  ierr = DMDAGetInfo(da,0,&mx,0,0,0,0,0,0,0,0,0,0,0);CHKERRQ(ierr);
  ierr = DMGetApplicationContext(da,&x);CHKERRQ(ierr);
  h    = 2.0*PETSC_PI/((mx));
  ierr = VecCopy(x,b);CHKERRQ(ierr);
  ierr = VecScale(b,h);CHKERRQ(ierr);
  PetscFunctionReturn(0);
}
Пример #2
0
// assemble the right-hand side of the system for the Lagrangian forces
PetscErrorCode RigidKinematicsSolver::assembleRHSForces()
{
    PetscErrorCode ierr;

    PetscFunctionBeginUser;

    ierr = PetscLogStagePush(stageRHSForces); CHKERRQ(ierr);

    // rhsf = UB - E u^{**}
    ierr = MatMult(E, solution->UGlobal, rhsf); CHKERRQ(ierr);
    ierr = VecScale(rhsf, -1.0); CHKERRQ(ierr);
    ierr = VecAYPX(rhsf, 1.0, UB); CHKERRQ(ierr);

    ierr = PetscLogStagePop(); CHKERRQ(ierr);

    PetscFunctionReturn(0);
}  // assembleRHSForces
Пример #3
0
PetscErrorCode PCApply_Noise(PC pc,Vec xin,Vec xout)
{
  PetscErrorCode ierr;
  PCNoise_Ctx    *ctx;
  PetscReal      nrmin, nrmnoise;

  PetscFunctionBeginUser;
  ierr = PCShellGetContext(pc,(void**)&ctx);CHKERRQ(ierr);

  /* xout is ||xin|| * ctx->eta*  f, where f is a pseudorandom unit vector
    (Note that this should always be combined additively with another PC) */
  ierr = VecSetRandom(xout,ctx->random);CHKERRQ(ierr);
  ierr = VecNorm(xin,NORM_2,&nrmin);CHKERRQ(ierr);
  ierr = VecNorm(xout,NORM_2,&nrmnoise);CHKERRQ(ierr);
  ierr = VecScale(xout,ctx->eta*(nrmin/nrmnoise));CHKERRQ(ierr);
  PetscFunctionReturn(0);
}
Пример #4
0
PetscErrorCode MatMult_SchurComplement(Mat N,Vec x,Vec y)
{
  Mat_SchurComplement *Na = (Mat_SchurComplement*)N->data;
  PetscErrorCode      ierr;

  PetscFunctionBegin;
  if (!Na->work1) {ierr = MatCreateVecs(Na->A,&Na->work1,NULL);CHKERRQ(ierr);}
  if (!Na->work2) {ierr = MatCreateVecs(Na->A,&Na->work2,NULL);CHKERRQ(ierr);}
  ierr = MatMult(Na->B,x,Na->work1);CHKERRQ(ierr);
  ierr = KSPSolve(Na->ksp,Na->work1,Na->work2);CHKERRQ(ierr);
  ierr = MatMult(Na->C,Na->work2,y);CHKERRQ(ierr);
  ierr = VecScale(y,-1.0);CHKERRQ(ierr);
  if (Na->D) {
    ierr = MatMultAdd(Na->D,x,y,y);CHKERRQ(ierr);
  }
  PetscFunctionReturn(0);
}
Пример #5
0
static PetscErrorCode TronGradientProjections(Tao tao,TAO_TRON *tron)
{
  PetscErrorCode                 ierr;
  PetscInt                       i;
  TaoLineSearchConvergedReason ls_reason;
  PetscReal                      actred=-1.0,actred_max=0.0;
  PetscReal                      f_new;
  /*
     The gradient and function value passed into and out of this
     routine should be current and correct.

     The free, active, and binding variables should be already identified
  */
  PetscFunctionBegin;
  if (tron->Free_Local) {
    ierr = ISDestroy(&tron->Free_Local);CHKERRQ(ierr);
  }
  ierr = VecWhichBetween(tao->XL,tao->solution,tao->XU,&tron->Free_Local);CHKERRQ(ierr);

  for (i=0;i<tron->maxgpits;i++){

    if ( -actred <= (tron->pg_ftol)*actred_max) break;

    tron->gp_iterates++; tron->total_gp_its++;
    f_new=tron->f;

    ierr = VecCopy(tao->gradient, tao->stepdirection);CHKERRQ(ierr);
    ierr = VecScale(tao->stepdirection, -1.0);CHKERRQ(ierr);
    ierr = TaoLineSearchSetInitialStepLength(tao->linesearch,tron->pgstepsize);CHKERRQ(ierr);
    ierr = TaoLineSearchApply(tao->linesearch, tao->solution, &f_new, tao->gradient, tao->stepdirection,
                              &tron->pgstepsize, &ls_reason);CHKERRQ(ierr);
    ierr = TaoAddLineSearchCounts(tao);CHKERRQ(ierr);


    /* Update the iterate */
    actred = f_new - tron->f;
    actred_max = PetscMax(actred_max,-(f_new - tron->f));
    tron->f = f_new;
    if (tron->Free_Local) {
      ierr = ISDestroy(&tron->Free_Local);CHKERRQ(ierr);
    }
    ierr = VecWhichBetween(tao->XL,tao->solution,tao->XU,&tron->Free_Local);CHKERRQ(ierr);
  }

  PetscFunctionReturn(0);
}
Пример #6
0
void FractalProjector::
new_vertex(Vertex* vrt, Edge* parent)
{
//	set the vertex to the center by calling the parents method
	RefinementCallbackLinear<APosition>::new_vertex(vrt, parent);

//	calculate the normal of the edge
	vector3 n;
	CalculateNormal(n, *m_pGrid, parent, m_aaPos);
//	first scale it to the same length as the edge, then scale it with the
//	given scaleFac
	number len = VecDistance(m_aaPos[parent->vertex(0)], m_aaPos[parent->vertex(1)]);
	VecScale (n, n, m_scaleFac * len);

//	offset the vertex by the calculated normal
	VecAdd(m_aaPos[vrt], m_aaPos[vrt], n);
}
Пример #7
0
PetscErrorCode MatGetDiagonal_Shell(Mat A,Vec v)
{
  Mat_Shell      *shell = (Mat_Shell*)A->data;
  PetscErrorCode ierr;

  PetscFunctionBegin;
  ierr = (*shell->getdiagonal)(A,v);CHKERRQ(ierr);
  ierr = VecScale(v,shell->vscale);CHKERRQ(ierr);
  if (shell->dshift) {
    ierr = VecPointwiseMult(v,v,shell->dshift);CHKERRQ(ierr);
  } else {
    ierr = VecShift(v,shell->vshift);CHKERRQ(ierr);
  }
  if (shell->left)  {ierr = VecPointwiseMult(v,v,shell->left);CHKERRQ(ierr);}
  if (shell->right) {ierr = VecPointwiseMult(v,v,shell->right);CHKERRQ(ierr);}
  PetscFunctionReturn(0);
}
Пример #8
0
Mapping *
LinearMappingCreate(
        Vector          *center,
        Vector          *vaxis,
        Vector          *uaxis)
{
	Mapping *res;
	RSMatrix m;
	Vector n;

	res = (Mapping *)Malloc(sizeof(Mapping));
	res->flags = OBJSPACE;
	res->method= LinearMapping;

	if (center)
		res->center = *center;
	else
		res->center.x = res->center.y = res->center.z = 0.;

	if (uaxis && vaxis) {
		VecCross(uaxis, vaxis, &n);
		/* this is wrong, since uaxis and vaxis
		 * give U and V in world space, and we
		 * need the inverse.
		 */
		ArbitraryMatrix(
			uaxis->x, uaxis->y, uaxis->z,
			vaxis->x, vaxis->y, vaxis->z,
			n.x, n.y, n.z,
			res->center.x, res->center.y, res->center.z,
			&m);
		MatrixInvert(&m, &res->m);
		res->uaxis = *uaxis;
		res->vaxis = *vaxis;
		VecNormalize(&res->uaxis);
		VecNormalize(&res->vaxis);
	} else {
		VecScale(-1., res->center, &n);
		TranslationMatrix(n.x, n.y, n.z, &res->m);
		res->uaxis.x = res->vaxis.y = 1.;
		res->uaxis.y = res->uaxis.z = res->vaxis.x =
			res->vaxis.z = 0.;
	}
	return res;
}
Пример #9
0
PetscErrorCode MatShift_Shell(Mat Y,PetscScalar a)
{
  Mat_Shell *shell = (Mat_Shell*)Y->data;
  PetscErrorCode ierr;

  PetscFunctionBegin;
  if (shell->left || shell->right || shell->dshift) {
    if (!shell->dshift) {
      if (!shell->dshift_owned) {ierr = VecDuplicate(shell->left ? shell->left : shell->right, &shell->dshift_owned);CHKERRQ(ierr);}
      shell->dshift = shell->dshift_owned;
      ierr = VecSet(shell->dshift,shell->vshift+a);CHKERRQ(ierr);
    } else {ierr = VecScale(shell->dshift,a);CHKERRQ(ierr);}
    if (shell->left)  {ierr = VecPointwiseDivide(shell->dshift,shell->dshift,shell->left);CHKERRQ(ierr);}
    if (shell->right) {ierr = VecPointwiseDivide(shell->dshift,shell->dshift,shell->right);CHKERRQ(ierr);}
  } else shell->vshift += a;
  ierr = MatShellUseScaledMethods(Y);CHKERRQ(ierr);
  PetscFunctionReturn(0);
}
Пример #10
0
static PetscErrorCode MatMultTranspose_SubMatrix(Mat N,Vec x,Vec y)
{
  Mat_SubMatrix  *Na = (Mat_SubMatrix*)N->data;
  Vec            xx  = 0;
  PetscErrorCode ierr;

  PetscFunctionBegin;
  ierr = PreScaleLeft(N,x,&xx);CHKERRQ(ierr);
  ierr = VecZeroEntries(Na->lwork);CHKERRQ(ierr);
  ierr = VecScatterBegin(Na->lrestrict,xx,Na->lwork,INSERT_VALUES,SCATTER_REVERSE);CHKERRQ(ierr);
  ierr = VecScatterEnd  (Na->lrestrict,xx,Na->lwork,INSERT_VALUES,SCATTER_REVERSE);CHKERRQ(ierr);
  ierr = MatMultTranspose(Na->A,Na->lwork,Na->rwork);CHKERRQ(ierr);
  ierr = VecScatterBegin(Na->rprolong,Na->rwork,y,INSERT_VALUES,SCATTER_REVERSE);CHKERRQ(ierr);
  ierr = VecScatterEnd  (Na->rprolong,Na->rwork,y,INSERT_VALUES,SCATTER_REVERSE);CHKERRQ(ierr);
  ierr = PostScaleRight(N,y);CHKERRQ(ierr);
  ierr = VecScale(y,Na->scale);CHKERRQ(ierr);
  PetscFunctionReturn(0);
}
Пример #11
0
static PetscErrorCode GPCGGradProjections(Tao tao)
{
  PetscErrorCode                 ierr;
  TAO_GPCG                       *gpcg = (TAO_GPCG *)tao->data;
  PetscInt                       i;
  PetscReal                      actred=-1.0,actred_max=0.0, gAg,gtg=gpcg->gnorm,alpha;
  PetscReal                      f_new,gdx,stepsize;
  Vec                            DX=tao->stepdirection,XL=tao->XL,XU=tao->XU,Work=gpcg->Work;
  Vec                            X=tao->solution,G=tao->gradient;
  TaoLineSearchConvergedReason lsflag=TAOLINESEARCH_CONTINUE_ITERATING;

  /*
     The free, active, and binding variables should be already identified
  */
  PetscFunctionBegin;
  for (i=0;i<gpcg->maxgpits;i++){
    if ( -actred <= (gpcg->pg_ftol)*actred_max) break;
    ierr = VecBoundGradientProjection(G,X,XL,XU,DX);CHKERRQ(ierr);
    ierr = VecScale(DX,-1.0);CHKERRQ(ierr);
    ierr = VecDot(DX,G,&gdx);CHKERRQ(ierr);

    ierr = MatMult(tao->hessian,DX,Work);CHKERRQ(ierr);
    ierr = VecDot(DX,Work,&gAg);CHKERRQ(ierr);

    gpcg->gp_iterates++;
    gpcg->total_gp_its++;

    gtg=-gdx;
    alpha = PetscAbsReal(gtg/gAg);
    ierr = TaoLineSearchSetInitialStepLength(tao->linesearch,alpha);CHKERRQ(ierr);
    f_new=gpcg->f;
    ierr = TaoLineSearchApply(tao->linesearch,X,&f_new,G,DX,&stepsize,&lsflag);CHKERRQ(ierr);

    /* Update the iterate */
    actred = f_new - gpcg->f;
    actred_max = PetscMax(actred_max,-(f_new - gpcg->f));
    gpcg->f = f_new;
    ierr = ISDestroy(&gpcg->Free_Local);CHKERRQ(ierr);
    ierr = VecWhichBetween(XL,X,XU,&gpcg->Free_Local);CHKERRQ(ierr);
  }

  gpcg->gnorm=gtg;
  PetscFunctionReturn(0);
} /* End gradient projections */
Пример #12
0
PetscErrorCode Update_q(Vec q,Vec u,Mat M_0,AppCtx *user)
{
  PetscErrorCode ierr;
  PetscScalar    *q_arr,*w_arr;
  PetscInt       i,n;

  PetscFunctionBeginUser;
  ierr = PetscLogEventBegin(event_update_q,0,0,0,0);CHKERRQ(ierr);
  ierr = MatMult(M_0,u,user->work1);CHKERRQ(ierr);
  ierr = VecScale(user->work1,-1.0);CHKERRQ(ierr);
  ierr = VecGetLocalSize(u,&n);CHKERRQ(ierr);
  ierr = VecGetArray(q,&q_arr);CHKERRQ(ierr);
  ierr = VecGetArray(user->work1,&w_arr);CHKERRQ(ierr);
  for (i=0; i<n; i++) q_arr[2*i]=q_arr[2*i+1] = w_arr[i];
  ierr = VecRestoreArray(q,&q_arr);CHKERRQ(ierr);
  ierr = VecRestoreArray(user->work1,&w_arr);CHKERRQ(ierr);
  ierr = PetscLogEventEnd(event_update_q,0,0,0,0);CHKERRQ(ierr);
  PetscFunctionReturn(0);
}
Пример #13
0
PetscErrorCode VecScale_MultiVec(Vec x, PetscScalar alpha)
{
#if !defined(NDEBUG)
    TBOX_ASSERT(x);
#endif
    Vec_MultiVec* mx = static_cast<Vec_MultiVec*>(x->data);
#if !defined(NDEBUG)
    TBOX_ASSERT(mx);
#endif
    PetscErrorCode ierr;
    for (PetscInt k = 0; k < mx->n; ++k)
    {
        ierr = VecScale(mx->array[k], alpha);
        CHKERRQ(ierr);
    }
    ierr = PetscObjectStateIncrease(reinterpret_cast<PetscObject>(x));
    CHKERRQ(ierr);
    PetscFunctionReturn(0);
} // VecScale_MultiVec
Пример #14
0
static PetscErrorCode TaoBQNLSComputeStep(Tao tao, PetscBool shift, KSPConvergedReason *ksp_reason, PetscInt *step_type)
{
  TAO_BNK        *bnk = (TAO_BNK *)tao->data;
  TAO_BQNK       *bqnk = (TAO_BQNK*)bnk->ctx;
  PetscErrorCode ierr;
  PetscInt       nupdates;

  PetscFunctionBegin;
  ierr = MatSolve(bqnk->B, tao->gradient, tao->stepdirection);CHKERRQ(ierr);
  ierr = VecScale(tao->stepdirection, -1.0);CHKERRQ(ierr);
  ierr = TaoBNKBoundStep(tao, bnk->as_type, tao->stepdirection);CHKERRQ(ierr);
  *ksp_reason = KSP_CONVERGED_ATOL;
  ierr = MatLMVMGetUpdateCount(bqnk->B, &nupdates);CHKERRQ(ierr);
  if (nupdates == 0) {
    *step_type = BNK_SCALED_GRADIENT;
  } else {
    *step_type = BNK_BFGS;
  }
  PetscFunctionReturn(0);
}
void ConvectionDiffusionFE<TDomain>::
lin_def_vector_source(const LocalVector& u,
                           std::vector<std::vector<MathVector<dim> > > vvvLinDef[],
                           const size_t nip)
{
//	request geometry
	const TFEGeom& geo = GeomProvider<TFEGeom>::get(m_lfeID, m_quadOrder);

//	loop integration points
	for(size_t ip = 0; ip < geo.num_ip(); ++ip)
	{
	//	loop test spaces
		for(size_t i = 0; i < geo.num_sh(); ++i)
		{
		//	add to local defect
			VecScale(vvvLinDef[ip][_C_][i], geo.global_grad(ip, i),
			         	 	 	 	 	 	 geo.weight(ip));
		}
	}
}
Пример #16
0
static PetscErrorCode PCBDDCApplyNullSpaceCorrectionPC(PC pc,Vec x,Vec y)
{
  NullSpaceCorrection_ctx pc_ctx;
  PetscErrorCode          ierr;

  PetscFunctionBegin;
  ierr = PCShellGetContext(pc,(void**)&pc_ctx);CHKERRQ(ierr);
  /* E */
  ierr = MatMultTranspose(pc_ctx->Lbasis_mat,x,pc_ctx->work_small_2);CHKERRQ(ierr);
  ierr = MatMultAdd(pc_ctx->Kbasis_mat,pc_ctx->work_small_2,x,pc_ctx->work_full_1);CHKERRQ(ierr);
  /* P^-1 */
  ierr = PCApply(pc_ctx->local_pc,pc_ctx->work_full_1,pc_ctx->work_full_2);CHKERRQ(ierr);
  /* E^T */
  ierr = MatMultTranspose(pc_ctx->Kbasis_mat,pc_ctx->work_full_2,pc_ctx->work_small_1);CHKERRQ(ierr);
  ierr = VecScale(pc_ctx->work_small_1,-1.0);CHKERRQ(ierr);
  ierr = MatMultAdd(pc_ctx->Lbasis_mat,pc_ctx->work_small_1,pc_ctx->work_full_2,pc_ctx->work_full_1);CHKERRQ(ierr);
  /* Sum contributions */
  ierr = MatMultAdd(pc_ctx->basis_mat,pc_ctx->work_small_2,pc_ctx->work_full_1,y);CHKERRQ(ierr);
  PetscFunctionReturn(0);
}
Пример #17
0
PetscErrorCode MatGetDiagonal_Composite(Mat A,Vec v)
{
  Mat_Composite     *shell = (Mat_Composite*)A->data;
  Mat_CompositeLink next   = shell->head;
  PetscErrorCode    ierr;

  PetscFunctionBegin;
  if (!next) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must provide at least one matrix with MatCompositeAddMat()");
  if (shell->right || shell->left) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Cannot get diagonal if left or right scaling");

  ierr = MatGetDiagonal(next->mat,v);CHKERRQ(ierr);
  if (next->next && !shell->work) {
    ierr = VecDuplicate(v,&shell->work);CHKERRQ(ierr);
  }
  while ((next = next->next)) {
    ierr = MatGetDiagonal(next->mat,shell->work);CHKERRQ(ierr);
    ierr = VecAXPY(v,1.0,shell->work);CHKERRQ(ierr);
  }
  ierr = VecScale(v,shell->scale);CHKERRQ(ierr);
  PetscFunctionReturn(0);
}
Пример #18
0
typename ntree<tree_dim, world_dim, elem_t, common_data_t>::vector_t
ntree<tree_dim, world_dim, elem_t, common_data_t>::
calculate_center_of_mass(Node& node)
{
	vector_t centerOfMass;
	VecSet(centerOfMass, 0);

	for(size_t entryInd = node.firstEntryInd; entryInd != s_invalidIndex;){
		Entry& entry = m_entries[entryInd];

		vector_t center;
		traits::calculate_center(center, entry.elem, m_commonData);
		VecAdd(centerOfMass, centerOfMass, center);
		entryInd = entry.nextEntryInd;
	}

	if(node.numEntries > 0)
		VecScale(centerOfMass, centerOfMass, (real_t)1 / (real_t)node.numEntries);

	return centerOfMass;
}
Пример #19
0
PetscErrorCode DPsi(AppCtx *user)
{
  PetscErrorCode ierr;
  PetscScalar    Evf=user->Evf,A=user->A,B=user->B,cv0=user->cv0;
  PetscScalar    *cv_p,*eta_p,*logcv_p,*logcv2_p,*DPsiv_p,*DPsieta_p;
  PetscInt       n,i;

  PetscFunctionBeginUser;
  ierr = VecGetLocalSize(user->cv,&n);
  ierr = VecGetArray(user->cv,&cv_p);CHKERRQ(ierr);
  ierr = VecGetArray(user->eta,&eta_p);CHKERRQ(ierr);
  ierr = VecGetArray(user->logcv,&logcv_p);CHKERRQ(ierr);
  ierr = VecGetArray(user->logcv2,&logcv2_p);CHKERRQ(ierr);
  ierr = VecGetArray(user->DPsiv,&DPsiv_p);CHKERRQ(ierr);
  ierr = VecGetArray(user->DPsieta,&DPsieta_p);CHKERRQ(ierr);

  ierr = Llog(user->cv,user->logcv);CHKERRQ(ierr);

  ierr = VecCopy(user->cv,user->work1);CHKERRQ(ierr);
  ierr = VecScale(user->work1,-1.0);CHKERRQ(ierr);
  ierr = VecShift(user->work1,1.0);CHKERRQ(ierr);
  ierr = Llog(user->work1,user->logcv2);CHKERRQ(ierr);

  for (i=0; i<n; i++)
  {
    DPsiv_p[i] = (eta_p[i]-1.0)*(eta_p[i]-1.0)*(eta_p[i]+1.0)*(eta_p[i]+1.0)*(Evf + logcv_p[i] - logcv2_p[i]) - 2.0*A*(cv_p[i] - cv0)*eta_p[i]*(eta_p[i]+2.0)*(eta_p[i]-1.0)*(eta_p[i]-1.0) + 2.0*B*(cv_p[i] - 1.0)*eta_p[i]*eta_p[i];

    DPsieta_p[i] = 4.0*eta_p[i]*(eta_p[i]-1.0)*(eta_p[i]+1.0)*(Evf*cv_p[i] + cv_p[i]*logcv_p[i] + (1.0-cv_p[i])*logcv2_p[i]) - A*(cv_p[i] - cv0)*(cv_p[i] - cv0)*(4.0*eta_p[i]*eta_p[i]*eta_p[i] - 6.0*eta_p[i] + 2.0) + 2.0*B*(cv_p[i]-1.0)*(cv_p[i]-1.0)*eta_p[i];

  }

  ierr = VecRestoreArray(user->cv,&cv_p);CHKERRQ(ierr);
  ierr = VecRestoreArray(user->eta,&eta_p);CHKERRQ(ierr);
  ierr = VecGetArray(user->logcv,&logcv_p);CHKERRQ(ierr);
  ierr = VecGetArray(user->logcv2,&logcv2_p);CHKERRQ(ierr);
  ierr = VecRestoreArray(user->DPsiv,&DPsiv_p);CHKERRQ(ierr);
  ierr = VecRestoreArray(user->DPsieta,&DPsieta_p);CHKERRQ(ierr);
  PetscFunctionReturn(0);

}
Пример #20
0
PetscErrorCode StokesCalcResidual(Stokes* s) {
  PetscReal      val;
  Vec            b0, b1;
  PetscErrorCode ierr;

  PetscFunctionBeginUser;
  /* residual Ax-b (*warning* overwrites b) */
  ierr = VecScale(s->b, -1.0);
  CHKERRQ(ierr);
  ierr = MatMultAdd(s->A, s->x, s->b, s->b);
  CHKERRQ(ierr);
  /*  ierr = VecView(s->b, (PetscViewer)PETSC_VIEWER_DEFAULT);CHKERRQ(ierr); */

  /* residual velocity */
  ierr = VecGetSubVector(s->b, s->isg[0], &b0);
  CHKERRQ(ierr);
  ierr = VecNorm(b0, NORM_2, &val);
  CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, " residual u = %g\n", (double)val);
  CHKERRQ(ierr);
  ierr = VecRestoreSubVector(s->b, s->isg[0], &b0);
  CHKERRQ(ierr);

  /* residual pressure */
  ierr = VecGetSubVector(s->b, s->isg[1], &b1);
  CHKERRQ(ierr);
  ierr = VecNorm(b1, NORM_2, &val);
  CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, " residual p = %g\n", (double)val);
  CHKERRQ(ierr);
  ierr = VecRestoreSubVector(s->b, s->isg[1], &b1);
  CHKERRQ(ierr);

  /* total residual */
  ierr = VecNorm(s->b, NORM_2, &val);
  CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_WORLD, " residual [u,p] = %g\n", (double)val);
  CHKERRQ(ierr);
  PetscFunctionReturn(0);
}
Пример #21
0
// Matrix and Residual Fills
bool FiniteDifference::evaluate(FillType f,
                  const Vec* soln,
                  Vec* tmp_rhs,
                  Mat* tmp_matrix)
{
  flag = f;
  int ierr = 0;

  // Set the incoming linear objects
  if (flag == RHS_ONLY) {
    rhs = tmp_rhs;
  }
  else if (flag == MATRIX_ONLY) {
    A = tmp_matrix;
  }
  else if (flag == ALL) {
    rhs = tmp_rhs;
    A = tmp_matrix;
  }
  else {
    std::cout << "ERROR: FiniteDifference::fillMatrix() - No such flag as "
     << flag << std::endl;
    throw;
  }

  // Begin RHS fill
  if((flag == RHS_ONLY) || (flag == ALL)) {
    ierr = FormFunction(*snes, *soln, *rhs, ctx);CHKERRQ(ierr);
    PetscScalar minusOne = 1.0;
    ierr = VecScale( *rhs, minusOne );CHKERRQ(ierr);
  }

  // Begin Jacobian fill
  if((flag == MATRIX_ONLY) || (flag == ALL)) {
    ierr = FormJacobian(*snes, *soln, A, A, &matStruct, ctx);CHKERRQ(ierr);
  }

  return true;
}
Пример #22
0
PetscErrorCode MatMultAdd_SchurComplement(Mat N,Vec x,Vec y,Vec z)
{
  Mat_SchurComplement  *Na = (Mat_SchurComplement*)N->data;
  PetscErrorCode       ierr;

  PetscFunctionBegin;
  if (!Na->work1) {ierr = MatGetVecs(Na->A,&Na->work1,PETSC_NULL);CHKERRQ(ierr);}
  if (!Na->work2) {ierr = MatGetVecs(Na->A,&Na->work2,PETSC_NULL);CHKERRQ(ierr);}
  ierr = MatMult(Na->B,x,Na->work1);CHKERRQ(ierr);
  ierr = KSPSolve(Na->ksp,Na->work1,Na->work2);CHKERRQ(ierr);
  if (y == z) {
    ierr = VecScale(Na->work2,-1.0);CHKERRQ(ierr);
    ierr = MatMultAdd(Na->C,Na->work2,z,z);CHKERRQ(ierr);
  } else {
    ierr = MatMult(Na->C,Na->work2,z);CHKERRQ(ierr);
    ierr = VecAYPX(z,-1.0,y);CHKERRQ(ierr);
  }
  if (Na->D) {
    ierr = MatMultAdd(Na->D,x,z,z);CHKERRQ(ierr);
  }
  PetscFunctionReturn(0);
}
Пример #23
0
static PetscErrorCode SNESTSFormFunction_Alpha(SNES snes,Vec x,Vec y,TS ts)
{
  TS_Alpha       *th = (TS_Alpha*)ts->data;
  Vec            X0 = th->X0, V0 = th->V0;
  Vec            X1 = x, V1 = th->V1, R = y;
  PetscErrorCode ierr;

  PetscFunctionBegin;
  /* V1 = (1-1/Gamma)*V0 + 1/(Gamma*dT)*(X1-X0) */
  ierr = VecWAXPY(V1,-1,X0,X1);CHKERRQ(ierr);
  ierr = VecAXPBY(V1,1-1/th->Gamma,1/(th->Gamma*ts->time_step),V0);CHKERRQ(ierr);
  /* Xa = X0 + Alpha_f*(X1-X0) */
  ierr = VecWAXPY(th->Xa,-1,X0,X1);CHKERRQ(ierr);
  ierr = VecAYPX(th->Xa,th->Alpha_f,X0);CHKERRQ(ierr);
  /* Va = V0 + Alpha_m*(V1-V0) */
  ierr = VecWAXPY(th->Va,-1,V0,V1);CHKERRQ(ierr);
  ierr = VecAYPX(th->Va,th->Alpha_m,V0);CHKERRQ(ierr);
  /* F = Function(ta,Xa,Va) */
  ierr = TSComputeIFunction(ts,th->stage_time,th->Xa,th->Va,R,PETSC_FALSE);CHKERRQ(ierr);
  ierr = VecScale(R,1/th->Alpha_f);CHKERRQ(ierr);
  PetscFunctionReturn(0);
}
Пример #24
0
// Monitor a sub-region of the full-domain PETSc Vec object.
PetscErrorCode ProbeVolume::monitorVec(const DM &da,
                                       const Vec &fvec,
                                       const PetscInt &n,
                                       const PetscReal &t)
{
    PetscErrorCode ierr;

    PetscFunctionBeginUser;

    // grab the part of the vector that corresponds to the sub-volume
    Vec svec;
    ierr = VecGetSubVector(fvec, is, &svec); CHKERRQ(ierr);
    if (n_sum != 0)  // we accumulate the data over the time-steps
    {
        if (dvec == PETSC_NULL)
        {
            ierr = VecDuplicate(svec, &dvec); CHKERRQ(ierr);
            ierr = VecSet(dvec, 0.0); CHKERRQ(ierr);
        }
        ierr = VecAXPY(dvec, 1.0, svec); CHKERRQ(ierr);
        count++;
        if (count % n_sum == 0) // output the time-averaged data
        {
            ierr = VecScale(dvec, 1.0 / count); CHKERRQ(ierr);
            ierr = writeVec(dvec, t); CHKERRQ(ierr);
            // reset for the next accumulation cycle
            ierr = VecSet(dvec, 0.0); CHKERRQ(ierr);
            count = 0;
        }
    }
    else  // output the time-step sub-volume data to file
    {
        ierr = writeVec(svec, t); CHKERRQ(ierr);
    }
    ierr = VecRestoreSubVector(fvec, is, &svec); CHKERRQ(ierr);

    PetscFunctionReturn(0);
}  // ProbeVolume::monitorVec
Пример #25
0
PetscErrorCode MatMult_Advection(Mat A,Vec x,Vec y)
{
  AppCtx            *appctx;
  PetscErrorCode    ierr;
  PetscReal         **temp;
  PetscInt          j,xs,xn;
  Vec               xlocal,ylocal;
  const PetscScalar *xl;
  PetscScalar       *yl;
  PetscBLASInt      _One = 1,n;
  PetscScalar       _DOne = 1;  

  ierr = MatShellGetContext(A,&appctx);CHKERRQ(ierr);
  ierr = DMGetLocalVector(appctx->da,&xlocal);CHKERRQ(ierr);
  ierr = DMGlobalToLocalBegin(appctx->da,x,INSERT_VALUES,xlocal);CHKERRQ(ierr);
  ierr = DMGlobalToLocalEnd(appctx->da,x,INSERT_VALUES,xlocal);CHKERRQ(ierr);
  ierr = DMGetLocalVector(appctx->da,&ylocal);CHKERRQ(ierr);
  ierr = VecSet(ylocal,0.0);CHKERRQ(ierr);
  ierr = PetscGLLElementAdvectionCreate(&appctx->SEMop.gll,&temp);CHKERRQ(ierr);
  ierr = DMDAVecGetArrayRead(appctx->da,xlocal,(void*)&xl);CHKERRQ(ierr);
  ierr = DMDAVecGetArray(appctx->da,ylocal,&yl);CHKERRQ(ierr);
  ierr = DMDAGetCorners(appctx->da,&xs,NULL,NULL,&xn,NULL,NULL);CHKERRQ(ierr);
  ierr = PetscBLASIntCast(appctx->param.N,&n);CHKERRQ(ierr);
  for (j=xs; j<xs+xn; j += appctx->param.N-1) {
    PetscStackCallBLAS("BLASgemv",BLASgemv_("N",&n,&n,&_DOne,&temp[0][0],&n,&xl[j],&_One,&_DOne,&yl[j],&_One));
  }
  ierr = DMDAVecRestoreArrayRead(appctx->da,xlocal,(void*)&xl);CHKERRQ(ierr);
  ierr = DMDAVecRestoreArray(appctx->da,ylocal,&yl);CHKERRQ(ierr);
  ierr = PetscGLLElementAdvectionDestroy(&appctx->SEMop.gll,&temp);CHKERRQ(ierr);
  ierr = VecSet(y,0.0);CHKERRQ(ierr);
  ierr = DMLocalToGlobalBegin(appctx->da,ylocal,ADD_VALUES,y);CHKERRQ(ierr);
  ierr = DMLocalToGlobalEnd(appctx->da,ylocal,ADD_VALUES,y);CHKERRQ(ierr);
  ierr = DMRestoreLocalVector(appctx->da,&xlocal);CHKERRQ(ierr);
  ierr = DMRestoreLocalVector(appctx->da,&ylocal);CHKERRQ(ierr);
  ierr = VecPointwiseDivide(y,y,appctx->SEMop.mass);CHKERRQ(ierr);
  ierr = VecScale(y,-1.0);CHKERRQ(ierr);
  return 0;
}
Пример #26
0
/*@
   EPSGetEigenvector - Gets the i-th right eigenvector as computed by EPSSolve().

   Logically Collective on EPS

   Input Parameters:
+  eps - eigensolver context
-  i   - index of the solution

   Output Parameters:
+  Vr   - real part of eigenvector
-  Vi   - imaginary part of eigenvector

   Notes:
   If the corresponding eigenvalue is real, then Vi is set to zero. If PETSc is
   configured with complex scalars the eigenvector is stored
   directly in Vr (Vi is set to zero).

   The index i should be a value between 0 and nconv-1 (see EPSGetConverged()).
   Eigenpairs are indexed according to the ordering criterion established
   with EPSSetWhichEigenpairs().

   The 2-norm of the eigenvector is one unless the problem is generalized
   Hermitian. In this case the eigenvector is normalized with respect to the
   norm defined by the B matrix.

   Level: beginner

.seealso: EPSSolve(), EPSGetConverged(), EPSSetWhichEigenpairs(), EPSGetEigenpair()
@*/
PetscErrorCode EPSGetEigenvector(EPS eps,PetscInt i,Vec Vr,Vec Vi)
{
  PetscErrorCode ierr;
  PetscInt       k;

  PetscFunctionBegin;
  PetscValidHeaderSpecific(eps,EPS_CLASSID,1);
  PetscValidLogicalCollectiveInt(eps,i,2);
  PetscValidHeaderSpecific(Vr,VEC_CLASSID,3);
  PetscCheckSameComm(eps,1,Vr,3);
  if (Vi) { PetscValidHeaderSpecific(Vi,VEC_CLASSID,4); PetscCheckSameComm(eps,1,Vi,4); }
  EPSCheckSolved(eps,1);
  if (i<0 || i>=eps->nconv) SETERRQ(PetscObjectComm((PetscObject)eps),PETSC_ERR_ARG_OUTOFRANGE,"Argument 2 out of range");
  ierr = EPSComputeVectors(eps);CHKERRQ(ierr);
  if (!eps->perm) k = i;
  else k = eps->perm[i];
#if defined(PETSC_USE_COMPLEX)
  ierr = BVCopyVec(eps->V,k,Vr);CHKERRQ(ierr);
  if (Vi) { ierr = VecSet(Vi,0.0);CHKERRQ(ierr); }
#else
  if (eps->eigi[k] > 0) { /* first value of conjugate pair */
    ierr = BVCopyVec(eps->V,k,Vr);CHKERRQ(ierr);
    if (Vi) {
      ierr = BVCopyVec(eps->V,k+1,Vi);CHKERRQ(ierr);
    }
  } else if (eps->eigi[k] < 0) { /* second value of conjugate pair */
    ierr = BVCopyVec(eps->V,k-1,Vr);CHKERRQ(ierr);
    if (Vi) {
      ierr = BVCopyVec(eps->V,k,Vi);CHKERRQ(ierr);
      ierr = VecScale(Vi,-1.0);CHKERRQ(ierr);
    }
  } else { /* real eigenvalue */
    ierr = BVCopyVec(eps->V,k,Vr);CHKERRQ(ierr);
    if (Vi) { ierr = VecSet(Vi,0.0);CHKERRQ(ierr); }
  }
#endif
  PetscFunctionReturn(0);
}
Пример #27
0
PetscErrorCode H2PlusMatMultH(Mat H, Vec x, Vec y) {
  PetscErrorCode ierr;
  OceH2plus ctx;
  
  ierr = MatShellGetContext(H, &ctx); CHKERRQ(ierr);

  ierr = MatMatDecomposedMult(ctx->d2_r1, ctx->s_y1, x, y); CHKERRQ(ierr);
  ierr = VecScale(y, -0.5); CHKERRQ(ierr);

  Vec a; VecDuplicate(x, &a);  
  ierr = MatMatDecomposedMult(ctx->r2inv_r1, ctx->lambda_y1, x, a); CHKERRQ(ierr);
  ierr = VecAXPY(y, 0.5, a); CHKERRQ(ierr);
  ierr = VecDestroy(&a); CHKERRQ(ierr);

  for(int i = 0; i < ctx->nq; i++) {
    Vec b; VecDuplicate(x, &b);
    ierr = MatMatDecomposedMult(ctx->ne_r1[i], ctx->pq_y1[i], x, b); CHKERRQ(ierr);
    ierr = VecAXPY(y, -1.0, b);
    ierr = VecDestroy(&a); CHKERRQ(ierr);
  }

  return 0;
}
Пример #28
0
      virtual PetscErrorCode setup_RHS() override 
      {
        PetscErrorCode ierr;
        PetscFunctionBeginUser;

        ctx->compute_rhs = true;
        ctx->compute_singularity = true;

        ierr = MatMult(A, sol, rhs);CHKERRQ(ierr);
        ierr = VecScale(rhs, -1.);CHKERRQ(ierr);

        // dton_.ctx->compute_rhs = true;
        // dton_.ctx->add_rigid_motion = false;
        // dton_.ctx->compute_singularity = true;

        // ierr = dton_.solve_last_problem();CHKERRQ(ierr);

        // // save Stokes sol
        // ierr = VecCopy(dton_.problem_.sol, stokes_sol_save);CHKERRQ(ierr);
        // ierr = cafes::io::save_VTK("Resultats", "stokes_sol_rhs", dton_.problem_.sol, dton_.problem_.ctx->dm, dton_.problem_.ctx->h);CHKERRQ(ierr);

        PetscFunctionReturn(0);
      }
Пример #29
0
PetscErrorCode MatMultHermitian_Normal(Mat N,Vec x,Vec y)
{
  Mat_Normal     *Na = (Mat_Normal*)N->data;
  PetscErrorCode ierr;
  Vec            in;

  PetscFunctionBegin;
  in = x;
  if (Na->right) {
    if (!Na->rightwork) {
      ierr = VecDuplicate(Na->right,&Na->rightwork);CHKERRQ(ierr);
    }
    ierr = VecPointwiseMult(Na->rightwork,Na->right,in);CHKERRQ(ierr);
    in   = Na->rightwork;
  }
  ierr = MatMult(Na->A,in,Na->w);CHKERRQ(ierr);
  ierr = MatMultHermitianTranspose(Na->A,Na->w,y);CHKERRQ(ierr);
  if (Na->left) {
    ierr = VecPointwiseMult(y,Na->left,y);CHKERRQ(ierr);
  }
  ierr = VecScale(y,Na->scale);CHKERRQ(ierr);
  PetscFunctionReturn(0);
}
Пример #30
0
PetscErrorCode cHamiltonianMatrix::KernalPolynomialMethod(){
	int cutoff0 = int(1.5*a_scaling*tmax);
	if (rank==0) cout << "cutoff is chosen as " << cutoff0 << endl;
	ierr = VecDuplicate(X1,&X3);CHKERRQ(ierr);
	ierr = VecDuplicateVecs(X1,Nt,&WFt);CHKERRQ(ierr);
	for(int i = 0; i<Nt; ++i) {ierr = VecZeroEntries(WFt[i]);CHKERRQ(ierr);}

	/* //view matrix or vector
	PetscViewer viewer;
        PetscViewerASCIIOpen(PETSC_COMM_WORLD, NULL, &viewer);
        PetscViewerSetFormat(viewer, PETSC_VIEWER_ASCII_DENSE);
	*/
	ierr = VecCopy(X1,X3);CHKERRQ(ierr);  // TODO: avoid the copy for efficiency.
	WaveFunctionUpdate(0);
	//if (rank==0) cout<< "iter_k="<< 1 <<": X3=" << endl;
	//VecView(X3,viewer);
	ierr = MatMult(Hpolaron,X1,X2);CHKERRQ(ierr);
	ierr = VecCopy(X2,X3);CHKERRQ(ierr);	// TODO: avoid the copy for efficiency.
	WaveFunctionUpdate(1);
	//if (rank==0) cout<< "iter_k="<< 2 <<": X3=" << endl;
	//VecView(X3,viewer);
	for (int iter_k = 2; iter_k <= cutoff0; ++iter_k) {
		ierr = MatMult(Hpolaron,X2,X3);CHKERRQ(ierr);
		ierr = VecScale(X3,2.0);CHKERRQ(ierr);
		ierr = VecAXPY(X3,-1.0,X1);CHKERRQ(ierr);
		WaveFunctionUpdate(iter_k);
		/*	if (iter_k==1000) {
		  if (rank==0) cout<< "iter_k="<< iter_k+1 <<": X3=" << endl;
		  VecView(X3,viewer);
		  }*/
		ierr = VecCopy(X2,X1);CHKERRQ(ierr);
		ierr = VecCopy(X3,X2);CHKERRQ(ierr);
		if(iter_k%int(cutoff0*0.1)==0) if (rank==0) cout << iter_k << "th iteration within total of " << cutoff0 << " cutoff has finished." << endl;
	}
	/*PetscViewerDestroy(&viewer);*/
	return ierr;
}