PetscErrorCode PetscSectionVecView_ASCII(PetscSection s, Vec v, PetscViewer viewer) { PetscScalar *array; PetscInt p, i; PetscMPIInt rank; PetscErrorCode ierr; PetscFunctionBegin; ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)viewer), &rank);CHKERRQ(ierr); ierr = VecGetArray(v, &array);CHKERRQ(ierr); ierr = PetscViewerASCIISynchronizedAllow(viewer, PETSC_TRUE);CHKERRQ(ierr); ierr = PetscViewerASCIISynchronizedPrintf(viewer, "Process %d:\n", rank);CHKERRQ(ierr); for (p = 0; p < s->pEnd - s->pStart; ++p) { if ((s->bc) && (s->bc->atlasDof[p] > 0)) { PetscInt b; ierr = PetscViewerASCIISynchronizedPrintf(viewer, " (%4d) dim %2d offset %3d", p+s->pStart, s->atlasDof[p], s->atlasOff[p]);CHKERRQ(ierr); for (i = s->atlasOff[p]; i < s->atlasOff[p]+s->atlasDof[p]; ++i) { PetscScalar v = array[i]; #if defined(PETSC_USE_COMPLEX) if (PetscImaginaryPart(v) > 0.0) { ierr = PetscViewerASCIISynchronizedPrintf(viewer," %g + %g i", (double)PetscRealPart(v), (double)PetscImaginaryPart(v));CHKERRQ(ierr); } else if (PetscImaginaryPart(v) < 0.0) { ierr = PetscViewerASCIISynchronizedPrintf(viewer," %g - %g i", (double)PetscRealPart(v),(double)(-PetscImaginaryPart(v)));CHKERRQ(ierr); } else { ierr = PetscViewerASCIISynchronizedPrintf(viewer, " %g", (double)PetscRealPart(v));CHKERRQ(ierr); } #else ierr = PetscViewerASCIISynchronizedPrintf(viewer, " %g", (double)v);CHKERRQ(ierr); #endif } ierr = PetscViewerASCIISynchronizedPrintf(viewer, " constrained");CHKERRQ(ierr); for (b = 0; b < s->bc->atlasDof[p]; ++b) { ierr = PetscViewerASCIISynchronizedPrintf(viewer, " %d", s->bcIndices[s->bc->atlasOff[p]+b]);CHKERRQ(ierr); } ierr = PetscViewerASCIISynchronizedPrintf(viewer, "\n");CHKERRQ(ierr); } else { ierr = PetscViewerASCIISynchronizedPrintf(viewer, " (%4d) dim %2d offset %3d", p+s->pStart, s->atlasDof[p], s->atlasOff[p]);CHKERRQ(ierr); for (i = s->atlasOff[p]; i < s->atlasOff[p]+s->atlasDof[p]; ++i) { PetscScalar v = array[i]; #if defined(PETSC_USE_COMPLEX) if (PetscImaginaryPart(v) > 0.0) { ierr = PetscViewerASCIISynchronizedPrintf(viewer," %g + %g i", (double)PetscRealPart(v), (double)PetscImaginaryPart(v));CHKERRQ(ierr); } else if (PetscImaginaryPart(v) < 0.0) { ierr = PetscViewerASCIISynchronizedPrintf(viewer," %g - %g i", (double)PetscRealPart(v),(double)(-PetscImaginaryPart(v)));CHKERRQ(ierr); } else { ierr = PetscViewerASCIISynchronizedPrintf(viewer, " %g", (double)PetscRealPart(v));CHKERRQ(ierr); } #else ierr = PetscViewerASCIISynchronizedPrintf(viewer, " %g", (double)v);CHKERRQ(ierr); #endif } ierr = PetscViewerASCIISynchronizedPrintf(viewer, "\n");CHKERRQ(ierr); } } ierr = PetscViewerFlush(viewer);CHKERRQ(ierr); ierr = VecRestoreArray(v, &array);CHKERRQ(ierr); PetscFunctionReturn(0); }
/*@ PetscRandomSetFromOptions - Configures the random number generator from the options database. Collective on PetscRandom Input Parameter: . rnd - The random number generator context Options Database: + -random_seed <integer> - provide a seed to the random number generater - -random_no_imaginary_part - makes the imaginary part of the random number zero, this is useful when you want the same code to produce the same result when run with real numbers or complex numbers for regression testing purposes Notes: To see all options, run your program with the -help option. Must be called after PetscRandomCreate() but before the rnd is used. Level: beginner .keywords: PetscRandom, set, options, database .seealso: PetscRandomCreate(), PetscRandomSetType() @*/ PetscErrorCode PetscRandomSetFromOptions(PetscRandom rnd) { PetscErrorCode ierr; PetscBool set,noimaginary = PETSC_FALSE; PetscInt seed; PetscFunctionBegin; PetscValidHeaderSpecific(rnd,PETSC_RANDOM_CLASSID,1); ierr = PetscObjectOptionsBegin((PetscObject)rnd); CHKERRQ(ierr); /* Handle PetscRandom type options */ ierr = PetscRandomSetTypeFromOptions_Private(PetscOptionsObject,rnd); CHKERRQ(ierr); /* Handle specific random generator's options */ if (rnd->ops->setfromoptions) { ierr = (*rnd->ops->setfromoptions)(PetscOptionsObject,rnd); CHKERRQ(ierr); } ierr = PetscOptionsInt("-random_seed","Seed to use to generate random numbers","PetscRandomSetSeed",0,&seed,&set); CHKERRQ(ierr); if (set) { ierr = PetscRandomSetSeed(rnd,(unsigned long int)seed); CHKERRQ(ierr); ierr = PetscRandomSeed(rnd); CHKERRQ(ierr); } ierr = PetscOptionsBool("-random_no_imaginary_part","The imaginary part of the random number will be zero","PetscRandomSetInterval",noimaginary,&noimaginary,&set); CHKERRQ(ierr); #if defined(PETSC_HAVE_COMPLEX) if (set) { if (noimaginary) { PetscScalar low,high; ierr = PetscRandomGetInterval(rnd,&low,&high); CHKERRQ(ierr); low = low - PetscImaginaryPart(low); high = high - PetscImaginaryPart(high); ierr = PetscRandomSetInterval(rnd,low,high); CHKERRQ(ierr); } } #endif ierr = PetscOptionsEnd(); CHKERRQ(ierr); ierr = PetscRandomViewFromOptions(rnd,NULL, "-random_view"); CHKERRQ(ierr); PetscFunctionReturn(0); }
std::pair<Real, Real> SlepcEigenSolver<T>::get_eigenpair(unsigned int i, NumericVector<T> &solution_in) { int ierr=0; PetscReal re, im; // Make sure the NumericVector passed in is really a PetscVector PetscVector<T>* solution = libmesh_cast_ptr<PetscVector<T>*>(&solution_in); // real and imaginary part of the ith eigenvalue. PetscScalar kr, ki; solution->close(); ierr = EPSGetEigenpair(_eps, i, &kr, &ki, solution->vec(), PETSC_NULL); LIBMESH_CHKERRABORT(ierr); #ifdef LIBMESH_USE_COMPLEX_NUMBERS re = PetscRealPart(kr); im = PetscImaginaryPart(kr); #else re = kr; im = ki; #endif return std::make_pair(re, im); }
PetscErrorCode PETSC_DLLEXPORT PetscRandomGetValue_Rand48(PetscRandom r,PetscScalar *val) { PetscFunctionBegin; #if defined(PETSC_USE_COMPLEX) if (r->iset) { *val = PetscRealPart(r->width)*drand48() + PetscRealPart(r->low) + (PetscImaginaryPart(r->width)*drand48() + PetscImaginaryPart(r->low)) * PETSC_i; } else { *val = drand48() + drand48()*PETSC_i; } #else if (r->iset) *val = r->width * drand48() + r->low; else *val = drand48(); #endif PetscFunctionReturn(0); }
std::pair<Real, Real> SlepcEigenSolver<T>::get_eigenpair(dof_id_type i, NumericVector<T> & solution_in) { PetscErrorCode ierr=0; PetscReal re, im; // Make sure the NumericVector passed in is really a PetscVector PetscVector<T> * solution = dynamic_cast<PetscVector<T> *>(&solution_in); if (!solution) libmesh_error_msg("Error getting eigenvector: input vector must be a PetscVector."); // real and imaginary part of the ith eigenvalue. PetscScalar kr, ki; solution->close(); ierr = EPSGetEigenpair(_eps, i, &kr, &ki, solution->vec(), PETSC_NULL); LIBMESH_CHKERR(ierr); #ifdef LIBMESH_USE_COMPLEX_NUMBERS re = PetscRealPart(kr); im = PetscImaginaryPart(kr); #else re = kr; im = ki; #endif return std::make_pair(re, im); }
int testSlaterPotWithECS() { PrintTimeStamp(PETSC_COMM_SELF, "ECS", NULL); MPI_Comm comm = PETSC_COMM_SELF; BPS bps; BPSCreate(comm, &bps); BPSSetLine(bps, 100.0, 101); CScaling scaler; CScalingCreate(comm, &scaler); CScalingSetSharpECS(scaler, 60.0, 20.0*M_PI/180.0); int order = 5; BSS bss; BSSCreate(comm, &bss); BSSSetKnots(bss, order, bps); BSSSetCScaling(bss, scaler); BSSSetUp(bss); Pot slater; PotCreate(comm, &slater); PotSetSlater(slater, 7.5, 2, 1.0); if(getenv("SHOW_DEBUG")) BSSView(bss, PETSC_VIEWER_STDOUT_SELF); Mat H; BSSCreateR1Mat(bss, &H); Mat V; BSSCreateR1Mat(bss, &V); BSSPotR1Mat(bss, slater, V); Mat S; BSSCreateR1Mat(bss, &S); BSSSR1Mat(bss, S); BSSD2R1Mat(bss, H); MatScale(H, -0.5); MatAXPY(H, 1.0, V, DIFFERENT_NONZERO_PATTERN); EEPS eps; EEPSCreate(comm, &eps); EEPSSetOperators(eps, H, S); EEPSSetTarget(eps, 3.4); EPSSetDimensions(eps->eps, 10, PETSC_DEFAULT, PETSC_DEFAULT); EPSSetTolerances(eps->eps, PETSC_DEFAULT, 1000); // EPSSetType(eps, EPSARNOLDI); EEPSSolve(eps); PetscInt nconv; PetscScalar kr; EPSGetConverged(eps->eps, &nconv); ASSERT_TRUE(nconv > 0); if(getenv("SHOW_DEBUG")) for(int i = 0; i < nconv; i++) { EPSGetEigenpair(eps->eps, i, &kr, NULL, NULL, NULL); PetscPrintf(comm, "%f, %f\n", PetscRealPart(kr), PetscImaginaryPart(kr)); } EPSGetEigenpair(eps->eps, 0, &kr, NULL, NULL, NULL); PFDestroy(&slater); BSSDestroy(&bss); EEPSDestroy(&eps); MatDestroy(&H); MatDestroy(&V); MatDestroy(&S); // ASSERT_DOUBLE_NEAR(-0.0127745, PetscImaginaryPart(kr), pow(10.0, -4.0)); // ASSERT_DOUBLE_NEAR(3.4263903, PetscRealPart(kr), pow(10.0, -4.0)); return 0; }
PetscErrorCode HeaderlessBinaryReadCheck(DM dm,const char name[]) { PetscErrorCode ierr; int fdes; PetscScalar buffer[DMDA_I*DMDA_J*DMDA_K*3]; PetscInt len,d,i,j,k,M,N; PetscMPIInt rank; PetscBool dataverified = PETSC_TRUE; PetscFunctionBeginUser; ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr); ierr = DMDAGetInfo(dm,NULL,&M,&N,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);CHKERRQ(ierr); len = DMDA_I*DMDA_J*DMDA_K*3; if (!rank) { ierr = PetscBinaryOpen(name,FILE_MODE_READ,&fdes);CHKERRQ(ierr); ierr = PetscBinaryRead(fdes,buffer,len,PETSC_SCALAR);CHKERRQ(ierr); ierr = PetscBinaryClose(fdes);CHKERRQ(ierr); for (k=0; k<DMDA_K; k++) { for (j=0; j<DMDA_J; j++) { for (i=0; i<DMDA_I; i++) { for (d=0; d<3; d++) { PetscScalar v,test_value_s,test_value; PetscInt index; test_value_s = dmda_i_val[i]*((PetscScalar)i) + dmda_j_val[j]*((PetscScalar)(i+j*M)) + dmda_k_val[k]*((PetscScalar)(i + j*M + k*M*N)); test_value = 3.0 * test_value_s + (PetscScalar)d; index = 3*(i + j*M + k*M*N) + d; v = PetscAbsScalar(test_value-buffer[index]); #if defined(PETSC_USE_COMPLEX) if ((PetscRealPart(v) > 1.0e-10) || (PetscImaginaryPart(v) > 1.0e-10)) { ierr = PetscPrintf(PETSC_COMM_SELF,"ERROR: Difference > 1.0e-10 occurred (delta = (%+1.12e,%+1.12e) [loc %D,%D,%D(%D)])\n",(double)PetscRealPart(test_value),(double)PetscImaginaryPart(test_value),i,j,k,d);CHKERRQ(ierr); dataverified = PETSC_FALSE; } #else if (PetscRealPart(v) > 1.0e-10) { ierr = PetscPrintf(PETSC_COMM_SELF,"ERROR: Difference > 1.0e-10 occurred (delta = %+1.12e [loc %D,%D,%D(%D)])\n",(double)PetscRealPart(test_value),i,j,k,d);CHKERRQ(ierr); dataverified = PETSC_FALSE; } #endif } } } } if (dataverified) { ierr = PetscPrintf(PETSC_COMM_SELF,"Headerless read of data verified for: %s\n",name);CHKERRQ(ierr); } } PetscFunctionReturn(0); }
static PetscErrorCode PetscRandomGetValue_Rander48(PetscRandom r, PetscScalar *val) { PetscRandom_Rander48 *r48 = (PetscRandom_Rander48*)r->data; PetscFunctionBegin; #if defined(PETSC_USE_COMPLEX) if (r->iset) { *val = PetscRealPart(r->low) + PetscImaginaryPart(r->low) * PETSC_i; if (PetscRealPart(r->width)) { *val += PetscRealPart(r->width)* _dorander48(r48); } if (PetscImaginaryPart(r->width)) { *val += PetscImaginaryPart(r->width)* _dorander48(r48) * PETSC_i; } } else { *val = _dorander48(r48) + _dorander48(r48)*PETSC_i; } #else if (r->iset) *val = r->width * _dorander48(r48) + r->low; else *val = _dorander48(r48); #endif PetscFunctionReturn(0); }
int main(int argc, char **args) { PetscErrorCode ierr; MPI_Comm comm = PETSC_COMM_SELF; FEMInf fem; FEMInfCreate(comm, &fem); ViewerFunc viewer; ViewerFuncCreate(comm, &viewer); PetscReal w = 1.0; int L0 = 0; int L1 = 1; ierr = SlepcInitialize(&argc, &args, (char*)0, help); CHKERRQ(ierr); PrintTimeStamp(comm, "Init", NULL); PetscOptionsBegin(comm, "", "h_pi.c options", "none"); ierr = PetscOptionsGetInt(NULL, "-L0", &L0, NULL); CHKERRQ(ierr); ierr = PetscOptionsGetInt(NULL, "-L1", &L1, NULL); CHKERRQ(ierr); ierr = PetscOptionsGetReal(NULL, "-w", &w, NULL); CHKERRQ(ierr); ierr = FEMInfSetFromOptions(fem); CHKERRQ(ierr); ierr = ViewerFuncSetFromOptions(viewer); CHKERRQ(ierr); PetscOptionsEnd(); Vec x0, x1; PetscScalar e0, alpha; ierr = SolveInit(fem, L0, &e0, &x0); CHKERRQ(ierr); if(getenv("SHOW_DEBUG")) { printf("E0=%f\n", PetscRealPart(e0)); } ierr = SolveFinal(fem, L1, e0+w, x0, &x1, &alpha); CHKERRQ(ierr); FEMInfView(fem, PETSC_VIEWER_STDOUT_SELF); PetscPrintf(comm, "alpha: %f, %f\n", PetscRealPart(alpha), PetscImaginaryPart(alpha)); // ierr = PetscFOpen(comm, "tmp/h_pi_psi.dat", "w", &fp); CHKERRQ(ierr); ierr = FEMInfViewFunc(fem, x1, viewer); CHKERRQ(ierr); // ierr = PetscFClose(comm, fp); CHKERRQ(ierr); // ierr = FEMInfDestroy(&fem); CHKERRQ(ierr); return 0; }
std::pair<Real, Real> SlepcEigenSolver<T>::get_eigenvalue(unsigned int i) { int ierr=0; PetscReal re, im; // real and imaginary part of the ith eigenvalue. PetscScalar kr, ki; ierr = EPSGetEigenvalue(_eps, i, &kr, &ki); LIBMESH_CHKERRABORT(ierr); #ifdef LIBMESH_USE_COMPLEX_NUMBERS re = PetscRealPart(kr); im = PetscImaginaryPart(kr); #else re = kr; im = ki; #endif return std::make_pair(re, im); }
int main(int argc,char **argv) { PetscInt ierr,n,i; PetscScalar a,array[10]; PetscReal rarray[10]; PetscInitialize(&argc,&argv,(char*)0,help); ierr = PetscOptionsGetScalar(NULL,NULL,"-a",&a,NULL);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_SELF,"Scalar a = %g + %gi\n",(double)PetscRealPart(a),(double)PetscImaginaryPart(a));CHKERRQ(ierr); ierr = PetscOptionsBegin(PETSC_COMM_WORLD,NULL,"test options",NULL);CHKERRQ(ierr); n = 10; /* max num of input values */ ierr = PetscOptionsRealArray("-rarray", "Input a real array", "ex14.c", rarray, &n, NULL);CHKERRQ(ierr); if (n) { ierr = PetscPrintf(PETSC_COMM_SELF,"Real rarray of length %d\n",n);CHKERRQ(ierr); for (i=0; i<n; i++){ ierr = PetscPrintf(PETSC_COMM_SELF," %g,\n",rarray[i]);CHKERRQ(ierr); } } n = 10; /* max num of input values */ ierr = PetscOptionsScalarArray("-array", "Input a scalar array", "ex14.c", array, &n, NULL);CHKERRQ(ierr); if (n) { ierr = PetscPrintf(PETSC_COMM_SELF,"Scalar rarray of length %d\n",n);CHKERRQ(ierr); for (i=0; i<n; i++){ if (PetscImaginaryPart(array[i]) < 0.0) { ierr = PetscPrintf(PETSC_COMM_SELF," %g - %gi\n",(double)PetscRealPart(array[i]),(double)PetscAbsReal(PetscImaginaryPart(array[i])));CHKERRQ(ierr); } else { ierr = PetscPrintf(PETSC_COMM_SELF," %g + %gi\n",(double)PetscRealPart(array[i]),(double)PetscImaginaryPart(array[i]));CHKERRQ(ierr); } } } ierr = PetscOptionsEnd();CHKERRQ(ierr); ierr = PetscFinalize(); return 0; }
/*@C PetscBagRegisterScalar - add a real or complex number value to the bag Logically Collective on PetscBag Input Parameter: + bag - the bag of values . addr - location of scalar in struct . mdefault - the initial value . name - name of the variable - help - longer string with more information about the value Level: beginner .seealso: PetscBag, PetscBagSetName(), PetscBagView(), PetscBagLoad(), PetscBagGetData() PetscBagRegisterInt(), PetscBagRegisterBool(), PetscBagRegisterScalar() PetscBagSetFromOptions(), PetscBagCreate(), PetscBagGetName(), PetscBagRegisterEnum() @*/ PetscErrorCode PetscBagRegisterScalar(PetscBag bag,void *addr,PetscScalar mdefault,const char *name,const char *help) { PetscErrorCode ierr; PetscBagItem item; char nname[PETSC_BAG_NAME_LENGTH+1]; PetscBool printhelp; PetscFunctionBegin; nname[0] = '-'; nname[1] = 0; ierr = PetscStrncat(nname,name,PETSC_BAG_NAME_LENGTH-1);CHKERRQ(ierr); ierr = PetscOptionsHasName(NULL,"-help",&printhelp);CHKERRQ(ierr); if (printhelp) { ierr = (*PetscHelpPrintf)(bag->bagcomm," -%s%s <%g + %gi>: %s \n",bag->bagprefix ? bag->bagprefix : "",name,(double)PetscRealPart(mdefault),(double)PetscImaginaryPart(mdefault),help);CHKERRQ(ierr); } ierr = PetscOptionsGetScalar(bag->bagprefix,nname,&mdefault,NULL);CHKERRQ(ierr); ierr = PetscNew(&item);CHKERRQ(ierr); item->dtype = PETSC_SCALAR; item->offset = ((char*)addr) - ((char*)bag); if (item->offset > bag->bagsize) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Registered item %s %s is not in bag memory space",name,help); item->next = 0; item->msize = 1; *(PetscScalar*)addr = mdefault; ierr = PetscBagRegister_Private(bag,item,name,help);CHKERRQ(ierr); PetscFunctionReturn(0); }
/*@C PetscBagView - Views a bag of values as either ASCII text or a binary file Collective on PetscBag Input Parameter: + bag - the bag of values - viewer - location to view the values Level: beginner Warning: Currently PETSc bags saved in a binary file can only be read back in on a machine of the same architecture. Let us know when this is a problem and we'll fix it. .seealso: PetscBag, PetscBagSetName(), PetscBagDestroy(), PetscBagLoad(), PetscBagGetData() PetscBagRegisterReal(), PetscBagRegisterInt(), PetscBagRegisterBool(), PetscBagRegisterScalar(), PetscBagRegisterEnum() PetscBagSetFromOptions(), PetscBagCreate(), PetscBagGetName() @*/ PetscErrorCode PetscBagView(PetscBag bag,PetscViewer view) { PetscBool isascii,isbinary; PetscErrorCode ierr; PetscBagItem nitem = bag->bagitems; PetscFunctionBegin; ierr = PetscObjectTypeCompare((PetscObject)view,PETSCVIEWERASCII,&isascii);CHKERRQ(ierr); ierr = PetscObjectTypeCompare((PetscObject)view,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr); if (isascii) { if (bag->bagprefix) { ierr = PetscViewerASCIIPrintf(view,"PetscBag Object: %s (%s) %s\n",bag->bagname,bag->bagprefix,bag->baghelp);CHKERRQ(ierr); } else { ierr = PetscViewerASCIIPrintf(view,"PetscBag Object: %s %s\n",bag->bagname,bag->baghelp);CHKERRQ(ierr); } while (nitem) { if (nitem->dtype == PETSC_CHAR) { char *value = (char*)(((char*)bag) + nitem->offset); char tmp = value[nitem->msize-1]; /* special handling for fortran chars wihout null terminator */ value[nitem->msize-1] =0; ierr = PetscViewerASCIIPrintf(view," %s = %s; %s\n",nitem->name,value,nitem->help);CHKERRQ(ierr); value[nitem->msize-1] = tmp; } else if (nitem->dtype == PETSC_REAL) { PetscReal *value = (PetscReal*)(((char*)bag) + nitem->offset); PetscInt i; ierr = PetscViewerASCIIPrintf(view," %s = ",nitem->name);CHKERRQ(ierr); for (i=0; i<nitem->msize; i++) { ierr = PetscViewerASCIIPrintf(view,"%g ",(double)value[i]);CHKERRQ(ierr); } ierr = PetscViewerASCIIPrintf(view,"; %s\n",nitem->help);CHKERRQ(ierr); } else if (nitem->dtype == PETSC_SCALAR) { PetscScalar value = *(PetscScalar*)(((char*)bag) + nitem->offset); #if defined(PETSC_USE_COMPLEX) ierr = PetscViewerASCIIPrintf(view," %s = %g + %gi; %s\n",nitem->name,(double)PetscRealPart(value),(double)PetscImaginaryPart(value),nitem->help);CHKERRQ(ierr); #else ierr = PetscViewerASCIIPrintf(view," %s = %g; %s\n",nitem->name,(double)value,nitem->help);CHKERRQ(ierr); #endif } else if (nitem->dtype == PETSC_INT) { PetscInt i,*value = (PetscInt*)(((char*)bag) + nitem->offset); ierr = PetscViewerASCIIPrintf(view," %s = ",nitem->name);CHKERRQ(ierr); for (i=0; i<nitem->msize; i++) { ierr = PetscViewerASCIIPrintf(view,"%D ",value[i]);CHKERRQ(ierr); } ierr = PetscViewerASCIIPrintf(view,"; %s\n",nitem->help);CHKERRQ(ierr); } else if (nitem->dtype == PETSC_BOOL) { PetscBool *value = (PetscBool*)(((char*)bag) + nitem->offset); PetscInt i; /* some Fortran compilers use -1 as boolean */ ierr = PetscViewerASCIIPrintf(view," %s = ",nitem->name);CHKERRQ(ierr); for (i=0; i<nitem->msize; i++) { if (((int) value[i]) == -1) value[i] = PETSC_TRUE; /* the checks here with != PETSC_FALSE and PETSC_TRUE is a special case; here we truly demand that the value be 0 or 1 */ if (value[i] != PETSC_FALSE && value[i] != PETSC_TRUE) SETERRQ3(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Boolean value for %s %s is corrupt; integer value %d",nitem->name,nitem->help,value); ierr = PetscViewerASCIIPrintf(view," %s",PetscBools[value[i]]);CHKERRQ(ierr); } ierr = PetscViewerASCIIPrintf(view,"; %s\n",nitem->help);CHKERRQ(ierr); } else if (nitem->dtype == PETSC_ENUM) { PetscEnum value = *(PetscEnum*)(((char*)bag) + nitem->offset); PetscInt i = 0; while (nitem->list[i++]) ; ierr = PetscViewerASCIIPrintf(view," %s = %s; (%s) %s\n",nitem->name,nitem->list[value],nitem->list[i-3],nitem->help);CHKERRQ(ierr); } nitem = nitem->next; } } else if (isbinary) { PetscInt classid = PETSC_BAG_FILE_CLASSID, dtype; PetscInt deprecatedbagsize = 0; PetscViewerFormat format; ierr = PetscViewerBinaryWrite(view,&classid,1,PETSC_INT,PETSC_TRUE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(view,&deprecatedbagsize,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(view,&bag->count,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(view,bag->bagname,PETSC_BAG_NAME_LENGTH,PETSC_CHAR,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(view,bag->baghelp,PETSC_BAG_HELP_LENGTH,PETSC_CHAR,PETSC_FALSE);CHKERRQ(ierr); while (nitem) { ierr = PetscViewerBinaryWrite(view,&nitem->offset,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); dtype = (PetscInt)nitem->dtype; ierr = PetscViewerBinaryWrite(view,&dtype,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(view,nitem->name,PETSC_BAG_NAME_LENGTH,PETSC_CHAR,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(view,nitem->help,PETSC_BAG_HELP_LENGTH,PETSC_CHAR,PETSC_FALSE);CHKERRQ(ierr); ierr = PetscViewerBinaryWrite(view,&nitem->msize,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr); /* some Fortran compilers use -1 as boolean */ if (dtype == PETSC_BOOL && ((*(int*) (((char*)bag) + nitem->offset) == -1))) *(int*) (((char*)bag) + nitem->offset) = PETSC_TRUE; ierr = PetscViewerBinaryWrite(view,(((char*)bag) + nitem->offset),nitem->msize,nitem->dtype,PETSC_FALSE);CHKERRQ(ierr); if (dtype == PETSC_ENUM) { ierr = PetscViewerBinaryWriteStringArray(view,(char**)nitem->list);CHKERRQ(ierr); } nitem = nitem->next; } ierr = PetscViewerGetFormat(view,&format);CHKERRQ(ierr); if (format == PETSC_VIEWER_BINARY_MATLAB) { MPI_Comm comm; FILE *info; ierr = PetscObjectGetComm((PetscObject)view,&comm);CHKERRQ(ierr); ierr = PetscViewerBinaryGetInfoPointer(view,&info);CHKERRQ(ierr); ierr = PetscFPrintf(comm,info,"#--- begin code written by PetscViewerBinary for MATLAB format ---#\n");CHKERRQ(ierr); ierr = PetscFPrintf(comm,info,"#$$ Set.%s = PetscBinaryRead(fd);\n",bag->bagname);CHKERRQ(ierr); ierr = PetscFPrintf(comm,info,"#--- end code written by PetscViewerBinary for MATLAB format ---#\n\n");CHKERRQ(ierr); } } PetscFunctionReturn(0); }
PetscErrorCode test_axpy_dot_max( void ) { Vec x1,y1, x2,y2; Vec tmp_buf[2]; Vec X, Y; PetscReal real,real2; PetscScalar scalar; PetscInt index; PetscErrorCode ierr; PetscFunctionBegin; PetscPrintf( PETSC_COMM_WORLD, "\n\n============== %s ==============\n", PETSC_FUNCTION_NAME ); gen_test_vector( PETSC_COMM_WORLD, 4, 0, 1, &x1 ); gen_test_vector( PETSC_COMM_WORLD, 5, 10, 2, &x2 ); gen_test_vector( PETSC_COMM_WORLD, 4, 4, 3, &y1 ); gen_test_vector( PETSC_COMM_WORLD, 5, 5, 1, &y2 ); tmp_buf[0] = x1; tmp_buf[1] = x2; ierr = VecCreateNest(PETSC_COMM_WORLD,2,PETSC_NULL,tmp_buf,&X);CHKERRQ(ierr); ierr = VecAssemblyBegin(X);CHKERRQ(ierr); ierr = VecAssemblyEnd(X);CHKERRQ(ierr); ierr = VecDestroy(&x1);CHKERRQ(ierr); ierr = VecDestroy(&x2);CHKERRQ(ierr); tmp_buf[0] = y1; tmp_buf[1] = y2; ierr = VecCreateNest(PETSC_COMM_WORLD,2,PETSC_NULL,tmp_buf,&Y);CHKERRQ(ierr); ierr = VecAssemblyBegin(Y);CHKERRQ(ierr); ierr = VecAssemblyEnd(Y);CHKERRQ(ierr); ierr = VecDestroy(&y1);CHKERRQ(ierr); ierr = VecDestroy(&y2);CHKERRQ(ierr); PetscPrintf( PETSC_COMM_WORLD, "VecAXPY \n"); ierr = VecAXPY( Y, 1.0, X ); /* Y <- a X + Y */ ierr = VecNestGetSubVec( Y, 0, &y1 );CHKERRQ(ierr); ierr = VecNestGetSubVec( Y, 1, &y2 );CHKERRQ(ierr); PetscPrintf( PETSC_COMM_WORLD, "(1) y1 = \n" ); ierr = VecView( y1, PETSC_VIEWER_STDOUT_WORLD );CHKERRQ(ierr); PetscPrintf( PETSC_COMM_WORLD, "(1) y2 = \n" ); ierr = VecView( y2, PETSC_VIEWER_STDOUT_WORLD );CHKERRQ(ierr); ierr = VecDot( X,Y, &scalar );CHKERRQ(ierr); PetscPrintf( PETSC_COMM_WORLD, "X.Y = %lf + %lfi \n", PetscRealPart(scalar), PetscImaginaryPart(scalar) ); ierr = VecDotNorm2( X,Y, &scalar, &real2 );CHKERRQ(ierr); PetscPrintf( PETSC_COMM_WORLD, "X.Y = %lf + %lfi norm2(Y) = %lf\n", PetscRealPart(scalar), PetscImaginaryPart(scalar), real2); ierr = VecAXPY( Y, 1.0, X ); /* Y <- a X + Y */ ierr = VecNestGetSubVec( Y, 0, &y1 );CHKERRQ(ierr); ierr = VecNestGetSubVec( Y, 1, &y2 );CHKERRQ(ierr); PetscPrintf( PETSC_COMM_WORLD, "(2) y1 = \n" ); ierr = VecView( y1, PETSC_VIEWER_STDOUT_WORLD );CHKERRQ(ierr); PetscPrintf( PETSC_COMM_WORLD, "(2) y2 = \n" ); ierr = VecView( y2, PETSC_VIEWER_STDOUT_WORLD );CHKERRQ(ierr); ierr = VecDot( X,Y, &scalar );CHKERRQ(ierr); PetscPrintf( PETSC_COMM_WORLD, "X.Y = %lf + %lfi \n", PetscRealPart(scalar), PetscImaginaryPart(scalar) ); ierr = VecDotNorm2( X,Y, &scalar, &real2 );CHKERRQ(ierr); PetscPrintf( PETSC_COMM_WORLD, "X.Y = %lf + %lfi norm2(Y) = %lf\n", PetscRealPart(scalar), PetscImaginaryPart(scalar), real2); ierr = VecMax( X, &index, &real );CHKERRQ(ierr); PetscPrintf( PETSC_COMM_WORLD, "(max-X) = %f : index = %d \n", real, index ); ierr = VecMin( X, &index, &real );CHKERRQ(ierr); PetscPrintf( PETSC_COMM_WORLD, "(min-X) = %f : index = %d \n", real, index ); ierr = VecDestroy(&X);CHKERRQ(ierr); ierr = VecDestroy(&Y);CHKERRQ(ierr); PetscFunctionReturn(0); }
/* MatMult_MFFD - Default matrix-free form for Jacobian-vector product, y = F'(u)*a: y ~= (F(u + ha) - F(u))/h, where F = nonlinear function, as set by SNESSetFunction() u = current iterate h = difference interval */ static PetscErrorCode MatMult_MFFD(Mat mat,Vec a,Vec y) { MatMFFD ctx = (MatMFFD)mat->data; PetscScalar h; Vec w,U,F; PetscErrorCode ierr; PetscBool zeroa; PetscFunctionBegin; if (!ctx->current_u) SETERRQ(PetscObjectComm((PetscObject)mat),PETSC_ERR_ARG_WRONGSTATE,"MatMFFDSetBase() has not been called, this is often caused by forgetting to call \n\t\tMatAssemblyBegin/End on the first Mat in the SNES compute function"); /* We log matrix-free matrix-vector products separately, so that we can separate the performance monitoring from the cases that use conventional storage. We may eventually modify event logging to associate events with particular objects, hence alleviating the more general problem. */ ierr = PetscLogEventBegin(MATMFFD_Mult,a,y,0,0);CHKERRQ(ierr); w = ctx->w; U = ctx->current_u; F = ctx->current_f; /* Compute differencing parameter */ if (!((PetscObject)ctx)->type_name) { ierr = MatMFFDSetType(mat,MATMFFD_WP);CHKERRQ(ierr); ierr = MatSetFromOptions(mat);CHKERRQ(ierr); } ierr = (*ctx->ops->compute)(ctx,U,a,&h,&zeroa);CHKERRQ(ierr); if (zeroa) { ierr = VecSet(y,0.0);CHKERRQ(ierr); PetscFunctionReturn(0); } if (mat->erroriffailure && PetscIsInfOrNanScalar(h)) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_PLIB,"Computed Nan differencing parameter h"); if (ctx->checkh) { ierr = (*ctx->checkh)(ctx->checkhctx,U,a,&h);CHKERRQ(ierr); } /* keep a record of the current differencing parameter h */ ctx->currenth = h; #if defined(PETSC_USE_COMPLEX) ierr = PetscInfo2(mat,"Current differencing parameter: %g + %g i\n",(double)PetscRealPart(h),(double)PetscImaginaryPart(h));CHKERRQ(ierr); #else ierr = PetscInfo1(mat,"Current differencing parameter: %15.12e\n",h);CHKERRQ(ierr); #endif if (ctx->historyh && ctx->ncurrenth < ctx->maxcurrenth) { ctx->historyh[ctx->ncurrenth] = h; } ctx->ncurrenth++; #if defined(PETSC_USE_COMPLEX) if (ctx->usecomplex) h = PETSC_i*h; #endif /* w = u + ha */ if (ctx->drscale) { ierr = VecPointwiseMult(ctx->drscale,a,U);CHKERRQ(ierr); ierr = VecAYPX(U,h,w);CHKERRQ(ierr); } else { ierr = VecWAXPY(w,h,a,U);CHKERRQ(ierr); } /* compute func(U) as base for differencing; only needed first time in and not when provided by user */ if (ctx->ncurrenth == 1 && ctx->current_f_allocated) { ierr = (*ctx->func)(ctx->funcctx,U,F);CHKERRQ(ierr); } ierr = (*ctx->func)(ctx->funcctx,w,y);CHKERRQ(ierr); #if defined(PETSC_USE_COMPLEX) if (ctx->usecomplex) { ierr = VecImaginaryPart(y);CHKERRQ(ierr); h = PetscImaginaryPart(h); } else { ierr = VecAXPY(y,-1.0,F);CHKERRQ(ierr); } #else ierr = VecAXPY(y,-1.0,F);CHKERRQ(ierr); #endif ierr = VecScale(y,1.0/h);CHKERRQ(ierr); ierr = VecAXPBY(y,ctx->vshift,ctx->vscale,a);CHKERRQ(ierr); if (ctx->dlscale) { ierr = VecPointwiseMult(y,ctx->dlscale,y);CHKERRQ(ierr); } if (ctx->dshift) { if (!ctx->dshiftw) { ierr = VecDuplicate(y,&ctx->dshiftw);CHKERRQ(ierr); } ierr = VecPointwiseMult(ctx->dshift,a,ctx->dshiftw);CHKERRQ(ierr); ierr = VecAXPY(y,1.0,ctx->dshiftw);CHKERRQ(ierr); } if (mat->nullsp) {ierr = MatNullSpaceRemove(mat->nullsp,y);CHKERRQ(ierr);} ierr = PetscLogEventEnd(MATMFFD_Mult,a,y,0,0);CHKERRQ(ierr); PetscFunctionReturn(0); }
int main( int argc, char **argv ) { Mat A; /* operator matrix */ Vec x; EPS eps; /* eigenproblem solver context */ const EPSType type; PetscReal error, tol, re, im; PetscScalar kr, ki; PetscErrorCode ierr; PetscInt N, n=10, m, i, j, II, Istart, Iend, nev, maxit, its, nconv; PetscScalar w; PetscBool flag; SlepcInitialize(&argc,&argv,(char*)0,help); ierr = PetscOptionsGetInt(PETSC_NULL,"-n",&n,PETSC_NULL);CHKERRQ(ierr); ierr = PetscOptionsGetInt(PETSC_NULL,"-m",&m,&flag);CHKERRQ(ierr); if(!flag) m=n; N = n*m; ierr = PetscPrintf(PETSC_COMM_WORLD,"\nFiedler vector of a 2-D regular mesh, N=%d (%dx%d grid)\n\n",N,n,m);CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Compute the operator matrix that defines the eigensystem, Ax=kx In this example, A = L(G), where L is the Laplacian of graph G, i.e. Lii = degree of node i, Lij = -1 if edge (i,j) exists in G - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ ierr = MatCreate(PETSC_COMM_WORLD,&A);CHKERRQ(ierr); ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,N,N);CHKERRQ(ierr); ierr = MatSetFromOptions(A);CHKERRQ(ierr); ierr = MatGetOwnershipRange(A,&Istart,&Iend);CHKERRQ(ierr); for( II=Istart; II<Iend; II++ ) { i = II/n; j = II-i*n; w = 0.0; if(i>0) { ierr = MatSetValue(A,II,II-n,-1.0,INSERT_VALUES);CHKERRQ(ierr); w=w+1.0; } if(i<m-1) { ierr = MatSetValue(A,II,II+n,-1.0,INSERT_VALUES);CHKERRQ(ierr); w=w+1.0; } if(j>0) { ierr = MatSetValue(A,II,II-1,-1.0,INSERT_VALUES);CHKERRQ(ierr); w=w+1.0; } if(j<n-1) { ierr = MatSetValue(A,II,II+1,-1.0,INSERT_VALUES);CHKERRQ(ierr); w=w+1.0; } ierr = MatSetValue(A,II,II,w,INSERT_VALUES);CHKERRQ(ierr); } ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create the eigensolver and set various options - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Create eigensolver context */ ierr = EPSCreate(PETSC_COMM_WORLD,&eps);CHKERRQ(ierr); /* Set operators. In this case, it is a standard eigenvalue problem */ ierr = EPSSetOperators(eps,A,PETSC_NULL);CHKERRQ(ierr); ierr = EPSSetProblemType(eps,EPS_HEP);CHKERRQ(ierr); /* Select portion of spectrum */ ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_REAL);CHKERRQ(ierr); /* Set solver parameters at runtime */ ierr = EPSSetFromOptions(eps);CHKERRQ(ierr); /* Attach deflation space: in this case, the matrix has a constant nullspace, [1 1 ... 1]^T is the eigenvector of the zero eigenvalue */ ierr = MatGetVecs(A,&x,PETSC_NULL);CHKERRQ(ierr); ierr = VecSet(x,1.0);CHKERRQ(ierr); ierr = EPSSetDeflationSpace(eps,1,&x);CHKERRQ(ierr); ierr = VecDestroy(x); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Solve the eigensystem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ ierr = EPSSolve(eps);CHKERRQ(ierr); ierr = EPSGetIterationNumber(eps, &its);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD," Number of iterations of the method: %d\n",its);CHKERRQ(ierr); /* Optional: Get some information from the solver and display it */ ierr = EPSGetType(eps,&type);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD," Solution method: %s\n\n",type);CHKERRQ(ierr); ierr = EPSGetDimensions(eps,&nev,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD," Number of requested eigenvalues: %d\n",nev);CHKERRQ(ierr); ierr = EPSGetTolerances(eps,&tol,&maxit);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD," Stopping condition: tol=%.4g, maxit=%d\n",tol,maxit);CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Display solution and clean up - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Get number of converged approximate eigenpairs */ ierr = EPSGetConverged(eps,&nconv);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD," Number of converged approximate eigenpairs: %d\n\n",nconv); CHKERRQ(ierr); if (nconv>0) { /* Display eigenvalues and relative errors */ ierr = PetscPrintf(PETSC_COMM_WORLD, " k ||Ax-kx||/||kx||\n" " ----------------- ------------------\n" );CHKERRQ(ierr); for( i=0; i<nconv; i++ ) { /* Get converged eigenpairs: i-th eigenvalue is stored in kr (real part) and ki (imaginary part) */ ierr = EPSGetEigenpair(eps,i,&kr,&ki,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr); /* Compute the relative error associated to each eigenpair */ ierr = EPSComputeRelativeError(eps,i,&error);CHKERRQ(ierr); #ifdef PETSC_USE_COMPLEX re = PetscRealPart(kr); im = PetscImaginaryPart(kr); #else re = kr; im = ki; #endif if (im!=0.0) { ierr = PetscPrintf(PETSC_COMM_WORLD," %9f%+9f j %12g\n",re,im,error);CHKERRQ(ierr); } else { ierr = PetscPrintf(PETSC_COMM_WORLD," %12f %12g\n",re,error);CHKERRQ(ierr); } } ierr = PetscPrintf(PETSC_COMM_WORLD,"\n" );CHKERRQ(ierr); } /* Free work space */ ierr = EPSDestroy(eps);CHKERRQ(ierr); ierr = MatDestroy(A);CHKERRQ(ierr); ierr = SlepcFinalize();CHKERRQ(ierr); return 0; }
int main(int argc,char **args) { Mat A; PetscInt i; PetscErrorCode ierr; char file[PETSC_MAX_PATH_LEN]; PetscLogDouble numberOfFlops, tsolve1, tsolve2; EPS eps; /* eigenproblem solver context */ const EPSType type; PetscReal error,tol,re,im; PetscScalar kr,ki; Vec xr=0,xi=0; PetscInt nev,maxit,its,nconv; EPSWhich which; EPSProblemType problemType; PetscMPIInt rank; PetscMPIInt numberOfProcessors; PetscBool flg; PetscBool isComplex; PetscViewer fd; SlepcInitialize(&argc,&args,(char*)0,help); ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr); ierr = MPI_Comm_size(PETSC_COMM_WORLD,&numberOfProcessors);CHKERRQ(ierr); ierr = PetscOptionsGetString(PETSC_NULL,"-fin",file,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr); if (!flg) { SETERRQ(PETSC_COMM_WORLD,1,"Must indicate matrix file with the -fin option"); } /* Read file */ ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,file,FILE_MODE_READ,&fd);CHKERRQ(ierr); // Create matrix ierr = MatCreate(PETSC_COMM_WORLD,&A);CHKERRQ(ierr); ierr = MatSetFromOptions(A);CHKERRQ(ierr); // Load matrix from file ierr = MatLoad(A,fd);CHKERRQ(ierr); // Destroy viewer ierr = PetscViewerDestroy(&fd);CHKERRQ(ierr); // Assemble matrix ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); //ierr = PetscPrintf(PETSC_COMM_SELF,"Reading matrix completes.\n");CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create the eigensolver and set various options - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Create eigensolver context */ ierr = EPSCreate(PETSC_COMM_WORLD,&eps);CHKERRQ(ierr); /* Set operators. In this case, it is a standard eigenvalue problem */ ierr = EPSSetOperators(eps,A,PETSC_NULL);CHKERRQ(ierr); //ierr = EPSSetProblemType(eps,EPS_HEP);CHKERRQ(ierr); /* Set solver parameters at runtime */ ierr = EPSSetFromOptions(eps);CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Solve the eigensystem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ PetscTime(tsolve1); ierr = EPSSolve(eps);CHKERRQ(ierr); PetscTime(tsolve2); /* Optional: Get some information from the solver and display it */ ierr = EPSGetProblemType(eps, &problemType);CHKERRQ(ierr); ierr = EPSGetWhichEigenpairs(eps, &which);CHKERRQ(ierr); ierr = EPSGetDimensions(eps,&nev,PETSC_NULL,PETSC_NULL);CHKERRQ(ierr); ierr = EPSGetType(eps,&type);CHKERRQ(ierr); ierr = EPSGetTolerances(eps,&tol,&maxit);CHKERRQ(ierr); ierr = EPSGetConverged(eps,&nconv);CHKERRQ(ierr); ierr = EPSGetIterationNumber(eps,&its);CHKERRQ(ierr); ierr = PetscGetFlops(&numberOfFlops);CHKERRQ(ierr); #if defined(PETSC_USE_COMPLEX) isComplex = 1; #else isComplex = 0; #endif //Print output: ierr = PetscPrintf(PETSC_COMM_WORLD,"%D\t %D\t %D\t %D\t %D\t %.4G\t %s\t %D\t %D\t %F\t %2.1e\t",isComplex, numberOfProcessors, problemType, which, nev, tol, type, nconv, its, numberOfFlops, (tsolve2-tsolve1));CHKERRQ(ierr); if (nconv>0) { for (i=0;i<nconv;i++) { /* Get converged eigenpairs: i-th eigenvalue is stored in kr (real part) and ki (imaginary part) */ ierr = EPSGetEigenpair(eps,i,&kr,&ki,xr,xi);CHKERRQ(ierr); /* Compute the relative error associated to each eigenpair */ ierr = EPSComputeRelativeError(eps,i,&error);CHKERRQ(ierr); #if defined(PETSC_USE_COMPLEX) re = PetscRealPart(kr); im = PetscImaginaryPart(kr); #else re = kr; im = ki; #endif if (im!=0.0) { // ierr = PetscPrintf(PETSC_COMM_WORLD," %9F%+9F j %12G\n",re,im,error);CHKERRQ(ierr); } else { // ierr = PetscPrintf(PETSC_COMM_WORLD," %12F %12G\n",re,error);CHKERRQ(ierr); } ierr = PetscPrintf(PETSC_COMM_WORLD,"%12G\t", error);CHKERRQ(ierr); } } ierr = PetscPrintf(PETSC_COMM_WORLD,"\n");CHKERRQ(ierr); //Destructors ierr = MatDestroy(&A);CHKERRQ(ierr); //ierr = PetscFinalize(); ierr = SlepcFinalize();CHKERRQ(ierr); return 0; }
/*@ KSPComputeEigenvaluesExplicitly - Computes all of the eigenvalues of the preconditioned operator using LAPACK. Collective on KSP Input Parameter: + ksp - iterative context obtained from KSPCreate() - n - size of arrays r and c Output Parameters: + r - real part of computed eigenvalues - c - complex part of computed eigenvalues Notes: This approach is very slow but will generally provide accurate eigenvalue estimates. This routine explicitly forms a dense matrix representing the preconditioned operator, and thus will run only for relatively small problems, say n < 500. Many users may just want to use the monitoring routine KSPMonitorSingularValue() (which can be set with option -ksp_monitor_singular_value) to print the singular values at each iteration of the linear solve. The preconditoner operator, rhs vector, solution vectors should be set before this routine is called. i.e use KSPSetOperators(),KSPSolve() or KSPSetOperators() Level: advanced .keywords: KSP, compute, eigenvalues, explicitly .seealso: KSPComputeEigenvalues(), KSPMonitorSingularValue(), KSPComputeExtremeSingularValues(), KSPSetOperators(), KSPSolve() @*/ PetscErrorCode KSPComputeEigenvaluesExplicitly(KSP ksp,PetscInt nmax,PetscReal *r,PetscReal *c) { Mat BA; PetscErrorCode ierr; PetscMPIInt size,rank; MPI_Comm comm = ((PetscObject)ksp)->comm; PetscScalar *array; Mat A; PetscInt m,row,nz,i,n,dummy; const PetscInt *cols; const PetscScalar *vals; PetscFunctionBegin; ierr = KSPComputeExplicitOperator(ksp,&BA);CHKERRQ(ierr); ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr); ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr); ierr = MatGetSize(BA,&n,&n);CHKERRQ(ierr); if (size > 1) { /* assemble matrix on first processor */ ierr = MatCreate(((PetscObject)ksp)->comm,&A);CHKERRQ(ierr); if (!rank) { ierr = MatSetSizes(A,n,n,n,n);CHKERRQ(ierr); } else { ierr = MatSetSizes(A,0,0,n,n);CHKERRQ(ierr); } ierr = MatSetType(A,MATMPIDENSE);CHKERRQ(ierr); ierr = MatMPIDenseSetPreallocation(A,PETSC_NULL);CHKERRQ(ierr); ierr = PetscLogObjectParent(BA,A);CHKERRQ(ierr); ierr = MatGetOwnershipRange(BA,&row,&dummy);CHKERRQ(ierr); ierr = MatGetLocalSize(BA,&m,&dummy);CHKERRQ(ierr); for (i=0; i<m; i++) { ierr = MatGetRow(BA,row,&nz,&cols,&vals);CHKERRQ(ierr); ierr = MatSetValues(A,1,&row,nz,cols,vals,INSERT_VALUES);CHKERRQ(ierr); ierr = MatRestoreRow(BA,row,&nz,&cols,&vals);CHKERRQ(ierr); row++; } ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatDenseGetArray(A,&array);CHKERRQ(ierr); } else { ierr = MatDenseGetArray(BA,&array);CHKERRQ(ierr); } #if defined(PETSC_HAVE_ESSL) /* ESSL has a different calling sequence for dgeev() and zgeev() than standard LAPACK */ if (!rank) { PetscScalar sdummy,*cwork; PetscReal *work,*realpart; PetscBLASInt clen,idummy,lwork,bn,zero = 0; PetscInt *perm; #if !defined(PETSC_USE_COMPLEX) clen = n; #else clen = 2*n; #endif ierr = PetscMalloc(clen*sizeof(PetscScalar),&cwork);CHKERRQ(ierr); idummy = -1; /* unused */ bn = PetscBLASIntCast(n); lwork = 5*n; ierr = PetscMalloc(lwork*sizeof(PetscReal),&work);CHKERRQ(ierr); ierr = PetscMalloc(n*sizeof(PetscReal),&realpart);CHKERRQ(ierr); ierr = PetscFPTrapPush(PETSC_FP_TRAP_OFF);CHKERRQ(ierr); LAPACKgeev_(&zero,array,&bn,cwork,&sdummy,&idummy,&idummy,&bn,work,&lwork); ierr = PetscFPTrapPop();CHKERRQ(ierr); ierr = PetscFree(work);CHKERRQ(ierr); /* For now we stick with the convention of storing the real and imaginary components of evalues separately. But is this what we really want? */ ierr = PetscMalloc(n*sizeof(PetscInt),&perm);CHKERRQ(ierr); #if !defined(PETSC_USE_COMPLEX) for (i=0; i<n; i++) { realpart[i] = cwork[2*i]; perm[i] = i; } ierr = PetscSortRealWithPermutation(n,realpart,perm);CHKERRQ(ierr); for (i=0; i<n; i++) { r[i] = cwork[2*perm[i]]; c[i] = cwork[2*perm[i]+1]; } #else for (i=0; i<n; i++) { realpart[i] = PetscRealPart(cwork[i]); perm[i] = i; } ierr = PetscSortRealWithPermutation(n,realpart,perm);CHKERRQ(ierr); for (i=0; i<n; i++) { r[i] = PetscRealPart(cwork[perm[i]]); c[i] = PetscImaginaryPart(cwork[perm[i]]); } #endif ierr = PetscFree(perm);CHKERRQ(ierr); ierr = PetscFree(realpart);CHKERRQ(ierr); ierr = PetscFree(cwork);CHKERRQ(ierr); } #elif !defined(PETSC_USE_COMPLEX) if (!rank) { PetscScalar *work; PetscReal *realpart,*imagpart; PetscBLASInt idummy,lwork; PetscInt *perm; idummy = n; lwork = 5*n; ierr = PetscMalloc(2*n*sizeof(PetscReal),&realpart);CHKERRQ(ierr); imagpart = realpart + n; ierr = PetscMalloc(5*n*sizeof(PetscReal),&work);CHKERRQ(ierr); #if defined(PETSC_MISSING_LAPACK_GEEV) SETERRQ(((PetscObject)ksp)->comm,PETSC_ERR_SUP,"GEEV - Lapack routine is unavailable\nNot able to provide eigen values."); #else { PetscBLASInt lierr; PetscScalar sdummy; PetscBLASInt bn = PetscBLASIntCast(n); ierr = PetscFPTrapPush(PETSC_FP_TRAP_OFF);CHKERRQ(ierr); LAPACKgeev_("N","N",&bn,array,&bn,realpart,imagpart,&sdummy,&idummy,&sdummy,&idummy,work,&lwork,&lierr); if (lierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in LAPACK routine %d",(int)lierr); ierr = PetscFPTrapPop();CHKERRQ(ierr); } #endif ierr = PetscFree(work);CHKERRQ(ierr); ierr = PetscMalloc(n*sizeof(PetscInt),&perm);CHKERRQ(ierr); for (i=0; i<n; i++) { perm[i] = i;} ierr = PetscSortRealWithPermutation(n,realpart,perm);CHKERRQ(ierr); for (i=0; i<n; i++) { r[i] = realpart[perm[i]]; c[i] = imagpart[perm[i]]; } ierr = PetscFree(perm);CHKERRQ(ierr); ierr = PetscFree(realpart);CHKERRQ(ierr); } #else if (!rank) { PetscScalar *work,*eigs; PetscReal *rwork; PetscBLASInt idummy,lwork; PetscInt *perm; idummy = n; lwork = 5*n; ierr = PetscMalloc(5*n*sizeof(PetscScalar),&work);CHKERRQ(ierr); ierr = PetscMalloc(2*n*sizeof(PetscReal),&rwork);CHKERRQ(ierr); ierr = PetscMalloc(n*sizeof(PetscScalar),&eigs);CHKERRQ(ierr); #if defined(PETSC_MISSING_LAPACK_GEEV) SETERRQ(((PetscObject)ksp)->comm,PETSC_ERR_SUP,"GEEV - Lapack routine is unavailable\nNot able to provide eigen values."); #else { PetscBLASInt lierr; PetscScalar sdummy; PetscBLASInt nb = PetscBLASIntCast(n); ierr = PetscFPTrapPush(PETSC_FP_TRAP_OFF);CHKERRQ(ierr); LAPACKgeev_("N","N",&nb,array,&nb,eigs,&sdummy,&idummy,&sdummy,&idummy,work,&lwork,rwork,&lierr); if (lierr) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"Error in LAPACK routine %d",(int)lierr); ierr = PetscFPTrapPop();CHKERRQ(ierr); } #endif ierr = PetscFree(work);CHKERRQ(ierr); ierr = PetscFree(rwork);CHKERRQ(ierr); ierr = PetscMalloc(n*sizeof(PetscInt),&perm);CHKERRQ(ierr); for (i=0; i<n; i++) { perm[i] = i;} for (i=0; i<n; i++) { r[i] = PetscRealPart(eigs[i]);} ierr = PetscSortRealWithPermutation(n,r,perm);CHKERRQ(ierr); for (i=0; i<n; i++) { r[i] = PetscRealPart(eigs[perm[i]]); c[i] = PetscImaginaryPart(eigs[perm[i]]); } ierr = PetscFree(perm);CHKERRQ(ierr); ierr = PetscFree(eigs);CHKERRQ(ierr); } #endif if (size > 1) { ierr = MatDenseRestoreArray(A,&array);CHKERRQ(ierr); ierr = MatDestroy(&A);CHKERRQ(ierr); } else { ierr = MatDenseRestoreArray(BA,&array);CHKERRQ(ierr); } ierr = MatDestroy(&BA);CHKERRQ(ierr); PetscFunctionReturn(0); }
int main(int argc,char **argv) { PetscErrorCode ierr; DS ds; SlepcSC sc; PetscScalar *A,*B,*wr,*wi; PetscReal re,im; PetscInt i,j,n=10,ld; PetscViewer viewer; PetscBool verbose; SlepcInitialize(&argc,&argv,(char*)0,help); ierr = PetscOptionsGetInt(NULL,"-n",&n,NULL);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD,"Solve a Dense System of type GNHEP - dimension %D.\n",n);CHKERRQ(ierr); ierr = PetscOptionsHasName(NULL,"-verbose",&verbose);CHKERRQ(ierr); /* Create DS object */ ierr = DSCreate(PETSC_COMM_WORLD,&ds);CHKERRQ(ierr); ierr = DSSetType(ds,DSGNHEP);CHKERRQ(ierr); ierr = DSSetFromOptions(ds);CHKERRQ(ierr); ld = n+2; /* test leading dimension larger than n */ ierr = DSAllocate(ds,ld);CHKERRQ(ierr); ierr = DSSetDimensions(ds,n,0,0,0);CHKERRQ(ierr); /* Set up viewer */ ierr = PetscViewerASCIIGetStdout(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr); ierr = PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_INFO_DETAIL);CHKERRQ(ierr); ierr = DSView(ds,viewer);CHKERRQ(ierr); ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr); if (verbose) { ierr = PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB);CHKERRQ(ierr); } /* Fill A with Grcar matrix */ ierr = DSGetArray(ds,DS_MAT_A,&A);CHKERRQ(ierr); ierr = PetscMemzero(A,sizeof(PetscScalar)*ld*n);CHKERRQ(ierr); for (i=1;i<n;i++) A[i+(i-1)*ld]=-1.0; for (j=0;j<4;j++) { for (i=0;i<n-j;i++) A[i+(i+j)*ld]=1.0; } ierr = DSRestoreArray(ds,DS_MAT_A,&A);CHKERRQ(ierr); /* Fill B with an identity matrix */ ierr = DSGetArray(ds,DS_MAT_B,&B);CHKERRQ(ierr); ierr = PetscMemzero(B,sizeof(PetscScalar)*ld*n);CHKERRQ(ierr); for (i=0;i<n;i++) B[i+i*ld]=1.0; ierr = DSRestoreArray(ds,DS_MAT_B,&B);CHKERRQ(ierr); if (verbose) { ierr = PetscPrintf(PETSC_COMM_WORLD,"Initial - - - - - - - - -\n");CHKERRQ(ierr); ierr = DSView(ds,viewer);CHKERRQ(ierr); } /* Solve */ ierr = PetscMalloc2(n,&wr,n,&wi);CHKERRQ(ierr); ierr = DSGetSlepcSC(ds,&sc);CHKERRQ(ierr); sc->comparison = SlepcCompareLargestMagnitude; sc->comparisonctx = NULL; sc->map = NULL; sc->mapobj = NULL; ierr = DSSolve(ds,wr,wi);CHKERRQ(ierr); ierr = DSSort(ds,wr,wi,NULL,NULL,NULL);CHKERRQ(ierr); if (verbose) { ierr = PetscPrintf(PETSC_COMM_WORLD,"After solve - - - - - - - - -\n");CHKERRQ(ierr); ierr = DSView(ds,viewer);CHKERRQ(ierr); } /* Print eigenvalues */ ierr = PetscPrintf(PETSC_COMM_WORLD,"Computed eigenvalues =\n",n);CHKERRQ(ierr); for (i=0;i<n;i++) { #if defined(PETSC_USE_COMPLEX) re = PetscRealPart(wr[i]); im = PetscImaginaryPart(wr[i]); #else re = wr[i]; im = wi[i]; #endif if (PetscAbs(im)<1e-10) { ierr = PetscViewerASCIIPrintf(viewer," %.5f\n",(double)re);CHKERRQ(ierr); } else { ierr = PetscViewerASCIIPrintf(viewer," %.5f%+.5fi\n",(double)re,(double)im);CHKERRQ(ierr); } } ierr = PetscFree2(wr,wi);CHKERRQ(ierr); ierr = DSDestroy(&ds);CHKERRQ(ierr); ierr = SlepcFinalize(); return 0; }
PetscErrorCode MatFactorNumeric_SeqSpooles(Mat F,Mat A,const MatFactorInfo *info) { Mat_Spooles *lu = (Mat_Spooles*)(F)->spptr; ChvManager *chvmanager ; Chv *rootchv ; IVL *adjIVL; PetscErrorCode ierr; PetscInt nz,nrow=A->rmap->n,irow,nedges,neqns=A->cmap->n,*ai,*aj,i,*diag=0,fierr; PetscScalar *av; double cputotal,facops; #if defined(PETSC_USE_COMPLEX) PetscInt nz_row,*aj_tmp; PetscScalar *av_tmp; #else PetscInt *ivec1,*ivec2,j; double *dvec; #endif PetscBool isSeqAIJ,isMPIAIJ; PetscFunctionBegin; if (lu->flg == DIFFERENT_NONZERO_PATTERN) { /* first numeric factorization */ (F)->ops->solve = MatSolve_SeqSpooles; (F)->assembled = PETSC_TRUE; /* set Spooles options */ ierr = SetSpoolesOptions(A, &lu->options);CHKERRQ(ierr); lu->mtxA = InpMtx_new(); } /* copy A to Spooles' InpMtx object */ ierr = PetscObjectTypeCompare((PetscObject)A,MATSEQAIJ,&isSeqAIJ);CHKERRQ(ierr); ierr = PetscObjectTypeCompare((PetscObject)A,MATSEQAIJ,&isMPIAIJ);CHKERRQ(ierr); if (isSeqAIJ){ Mat_SeqAIJ *mat = (Mat_SeqAIJ*)A->data; ai=mat->i; aj=mat->j; av=mat->a; if (lu->options.symflag == SPOOLES_NONSYMMETRIC) { nz=mat->nz; } else { /* SPOOLES_SYMMETRIC || SPOOLES_HERMITIAN */ nz=(mat->nz + A->rmap->n)/2; diag=mat->diag; } } else { /* A is SBAIJ */ Mat_SeqSBAIJ *mat = (Mat_SeqSBAIJ*)A->data; ai=mat->i; aj=mat->j; av=mat->a; nz=mat->nz; } InpMtx_init(lu->mtxA, INPMTX_BY_ROWS, lu->options.typeflag, nz, 0); #if defined(PETSC_USE_COMPLEX) for (irow=0; irow<nrow; irow++) { if ( lu->options.symflag == SPOOLES_NONSYMMETRIC || !(isSeqAIJ || isMPIAIJ)){ nz_row = ai[irow+1] - ai[irow]; aj_tmp = aj + ai[irow]; av_tmp = av + ai[irow]; } else { nz_row = ai[irow+1] - diag[irow]; aj_tmp = aj + diag[irow]; av_tmp = av + diag[irow]; } for (i=0; i<nz_row; i++){ InpMtx_inputComplexEntry(lu->mtxA, irow, *aj_tmp++,PetscRealPart(*av_tmp),PetscImaginaryPart(*av_tmp)); av_tmp++; } } #else ivec1 = InpMtx_ivec1(lu->mtxA); ivec2 = InpMtx_ivec2(lu->mtxA); dvec = InpMtx_dvec(lu->mtxA); if ( lu->options.symflag == SPOOLES_NONSYMMETRIC || !isSeqAIJ){ for (irow = 0; irow < nrow; irow++){ for (i = ai[irow]; i<ai[irow+1]; i++) ivec1[i] = irow; } IVcopy(nz, ivec2, aj); DVcopy(nz, dvec, av); } else { nz = 0; for (irow = 0; irow < nrow; irow++){ for (j = diag[irow]; j<ai[irow+1]; j++) { ivec1[nz] = irow; ivec2[nz] = aj[j]; dvec[nz] = av[j]; nz++; } } } InpMtx_inputRealTriples(lu->mtxA, nz, ivec1, ivec2, dvec); #endif InpMtx_changeStorageMode(lu->mtxA, INPMTX_BY_VECTORS); if ( lu->options.msglvl > 0 ) { int err; printf("\n\n input matrix"); ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n input matrix");CHKERRQ(ierr); InpMtx_writeForHumanEye(lu->mtxA, lu->options.msgFile); err = fflush(lu->options.msgFile); if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fflush() failed on file"); } if ( lu->flg == DIFFERENT_NONZERO_PATTERN){ /* first numeric factorization */ /*--------------------------------------------------- find a low-fill ordering (1) create the Graph object (2) order the graph -------------------------------------------------------*/ if (lu->options.useQR){ adjIVL = InpMtx_adjForATA(lu->mtxA); } else { adjIVL = InpMtx_fullAdjacency(lu->mtxA); } nedges = IVL_tsize(adjIVL); lu->graph = Graph_new(); Graph_init2(lu->graph, 0, neqns, 0, nedges, neqns, nedges, adjIVL, NULL, NULL); if ( lu->options.msglvl > 2 ) { int err; if (lu->options.useQR){ ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n graph of A^T A");CHKERRQ(ierr); } else { ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n graph of the input matrix");CHKERRQ(ierr); } Graph_writeForHumanEye(lu->graph, lu->options.msgFile); err = fflush(lu->options.msgFile); if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fflush() failed on file"); } switch (lu->options.ordering) { case 0: lu->frontETree = orderViaBestOfNDandMS(lu->graph, lu->options.maxdomainsize, lu->options.maxzeros, lu->options.maxsize, lu->options.seed, lu->options.msglvl, lu->options.msgFile); break; case 1: lu->frontETree = orderViaMMD(lu->graph,lu->options.seed,lu->options.msglvl,lu->options.msgFile); break; case 2: lu->frontETree = orderViaMS(lu->graph, lu->options.maxdomainsize, lu->options.seed,lu->options.msglvl,lu->options.msgFile); break; case 3: lu->frontETree = orderViaND(lu->graph, lu->options.maxdomainsize, lu->options.seed,lu->options.msglvl,lu->options.msgFile); break; default: SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Unknown Spooles's ordering"); } if ( lu->options.msglvl > 0 ) { int err; ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n front tree from ordering");CHKERRQ(ierr); ETree_writeForHumanEye(lu->frontETree, lu->options.msgFile); err = fflush(lu->options.msgFile); if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fflush() failed on file"); } /* get the permutation, permute the front tree */ lu->oldToNewIV = ETree_oldToNewVtxPerm(lu->frontETree); lu->oldToNew = IV_entries(lu->oldToNewIV); lu->newToOldIV = ETree_newToOldVtxPerm(lu->frontETree); if (!lu->options.useQR) ETree_permuteVertices(lu->frontETree, lu->oldToNewIV); /* permute the matrix */ if (lu->options.useQR){ InpMtx_permute(lu->mtxA, NULL, lu->oldToNew); } else { InpMtx_permute(lu->mtxA, lu->oldToNew, lu->oldToNew); if ( lu->options.symflag == SPOOLES_SYMMETRIC) { InpMtx_mapToUpperTriangle(lu->mtxA); } #if defined(PETSC_USE_COMPLEX) if ( lu->options.symflag == SPOOLES_HERMITIAN ) { InpMtx_mapToUpperTriangleH(lu->mtxA); } #endif InpMtx_changeCoordType(lu->mtxA, INPMTX_BY_CHEVRONS); } InpMtx_changeStorageMode(lu->mtxA, INPMTX_BY_VECTORS); /* get symbolic factorization */ if (lu->options.useQR){ lu->symbfacIVL = SymbFac_initFromGraph(lu->frontETree, lu->graph); IVL_overwrite(lu->symbfacIVL, lu->oldToNewIV); IVL_sortUp(lu->symbfacIVL); ETree_permuteVertices(lu->frontETree, lu->oldToNewIV); } else { lu->symbfacIVL = SymbFac_initFromInpMtx(lu->frontETree, lu->mtxA); } if ( lu->options.msglvl > 2 ) { int err; ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n old-to-new permutation vector");CHKERRQ(ierr); IV_writeForHumanEye(lu->oldToNewIV, lu->options.msgFile); ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n new-to-old permutation vector");CHKERRQ(ierr); IV_writeForHumanEye(lu->newToOldIV, lu->options.msgFile); ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n front tree after permutation");CHKERRQ(ierr); ETree_writeForHumanEye(lu->frontETree, lu->options.msgFile); ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n input matrix after permutation");CHKERRQ(ierr); InpMtx_writeForHumanEye(lu->mtxA, lu->options.msgFile); ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n symbolic factorization");CHKERRQ(ierr); IVL_writeForHumanEye(lu->symbfacIVL, lu->options.msgFile); err = fflush(lu->options.msgFile); if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fflush() failed on file"); } lu->frontmtx = FrontMtx_new(); lu->mtxmanager = SubMtxManager_new(); SubMtxManager_init(lu->mtxmanager, NO_LOCK, 0); } else { /* new num factorization using previously computed symbolic factor */ if (lu->options.pivotingflag) { /* different FrontMtx is required */ FrontMtx_free(lu->frontmtx); lu->frontmtx = FrontMtx_new(); } else { FrontMtx_clearData (lu->frontmtx); } SubMtxManager_free(lu->mtxmanager); lu->mtxmanager = SubMtxManager_new(); SubMtxManager_init(lu->mtxmanager, NO_LOCK, 0); /* permute mtxA */ if (lu->options.useQR){ InpMtx_permute(lu->mtxA, NULL, lu->oldToNew); } else { InpMtx_permute(lu->mtxA, lu->oldToNew, lu->oldToNew); if ( lu->options.symflag == SPOOLES_SYMMETRIC ) { InpMtx_mapToUpperTriangle(lu->mtxA); } InpMtx_changeCoordType(lu->mtxA, INPMTX_BY_CHEVRONS); } InpMtx_changeStorageMode(lu->mtxA, INPMTX_BY_VECTORS); if ( lu->options.msglvl > 2 ) { ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n input matrix after permutation");CHKERRQ(ierr); InpMtx_writeForHumanEye(lu->mtxA, lu->options.msgFile); } } /* end of if( lu->flg == DIFFERENT_NONZERO_PATTERN) */ if (lu->options.useQR){ FrontMtx_init(lu->frontmtx, lu->frontETree, lu->symbfacIVL, lu->options.typeflag, SPOOLES_SYMMETRIC, FRONTMTX_DENSE_FRONTS, SPOOLES_NO_PIVOTING, NO_LOCK, 0, NULL, lu->mtxmanager, lu->options.msglvl, lu->options.msgFile); } else { FrontMtx_init(lu->frontmtx, lu->frontETree, lu->symbfacIVL, lu->options.typeflag, lu->options.symflag, FRONTMTX_DENSE_FRONTS, lu->options.pivotingflag, NO_LOCK, 0, NULL, lu->mtxmanager, lu->options.msglvl, lu->options.msgFile); } if ( lu->options.symflag == SPOOLES_SYMMETRIC ) { /* || SPOOLES_HERMITIAN ? */ if ( lu->options.patchAndGoFlag == 1 ) { lu->frontmtx->patchinfo = PatchAndGoInfo_new(); PatchAndGoInfo_init(lu->frontmtx->patchinfo, 1, lu->options.toosmall, lu->options.fudge, lu->options.storeids, lu->options.storevalues); } else if ( lu->options.patchAndGoFlag == 2 ) { lu->frontmtx->patchinfo = PatchAndGoInfo_new(); PatchAndGoInfo_init(lu->frontmtx->patchinfo, 2, lu->options.toosmall, lu->options.fudge, lu->options.storeids, lu->options.storevalues); } } /* numerical factorization */ chvmanager = ChvManager_new(); ChvManager_init(chvmanager, NO_LOCK, 1); DVfill(10, lu->cpus, 0.0); if (lu->options.useQR){ facops = 0.0 ; FrontMtx_QR_factor(lu->frontmtx, lu->mtxA, chvmanager, lu->cpus, &facops, lu->options.msglvl, lu->options.msgFile); if ( lu->options.msglvl > 1 ) { ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n factor matrix");CHKERRQ(ierr); ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n facops = %9.2f", facops);CHKERRQ(ierr); } } else { IVfill(20, lu->stats, 0); rootchv = FrontMtx_factorInpMtx(lu->frontmtx, lu->mtxA, lu->options.tau, 0.0, chvmanager, &fierr, lu->cpus,lu->stats,lu->options.msglvl,lu->options.msgFile); if (rootchv) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_MAT_LU_ZRPVT,"\n matrix found to be singular"); if (fierr >= 0) SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_LIB,"\n error encountered at front %D", fierr); if(lu->options.FrontMtxInfo){ ierr = PetscPrintf(PETSC_COMM_SELF,"\n %8d pivots, %8d pivot tests, %8d delayed rows and columns\n",lu->stats[0], lu->stats[1], lu->stats[2]);CHKERRQ(ierr); cputotal = lu->cpus[8] ; if ( cputotal > 0.0 ) { ierr = PetscPrintf(PETSC_COMM_SELF, "\n cpus cpus/totaltime" "\n initialize fronts %8.3f %6.2f" "\n load original entries %8.3f %6.2f" "\n update fronts %8.3f %6.2f" "\n assemble postponed data %8.3f %6.2f" "\n factor fronts %8.3f %6.2f" "\n extract postponed data %8.3f %6.2f" "\n store factor entries %8.3f %6.2f" "\n miscellaneous %8.3f %6.2f" "\n total time %8.3f \n", lu->cpus[0], 100.*lu->cpus[0]/cputotal, lu->cpus[1], 100.*lu->cpus[1]/cputotal, lu->cpus[2], 100.*lu->cpus[2]/cputotal, lu->cpus[3], 100.*lu->cpus[3]/cputotal, lu->cpus[4], 100.*lu->cpus[4]/cputotal, lu->cpus[5], 100.*lu->cpus[5]/cputotal, lu->cpus[6], 100.*lu->cpus[6]/cputotal, lu->cpus[7], 100.*lu->cpus[7]/cputotal, cputotal);CHKERRQ(ierr); } } } ChvManager_free(chvmanager); if ( lu->options.msglvl > 0 ) { int err; ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n factor matrix");CHKERRQ(ierr); FrontMtx_writeForHumanEye(lu->frontmtx, lu->options.msgFile); err = fflush(lu->options.msgFile); if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fflush() failed on file"); } if ( lu->options.symflag == SPOOLES_SYMMETRIC ) { /* || SPOOLES_HERMITIAN ? */ if ( lu->options.patchAndGoFlag == 1 ) { if ( lu->frontmtx->patchinfo->fudgeIV != NULL ) { if (lu->options.msglvl > 0 ){ ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n small pivots found at these locations");CHKERRQ(ierr); IV_writeForHumanEye(lu->frontmtx->patchinfo->fudgeIV, lu->options.msgFile); } } PatchAndGoInfo_free(lu->frontmtx->patchinfo); } else if ( lu->options.patchAndGoFlag == 2 ) { if (lu->options.msglvl > 0 ){ if ( lu->frontmtx->patchinfo->fudgeIV != NULL ) { ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n small pivots found at these locations");CHKERRQ(ierr); IV_writeForHumanEye(lu->frontmtx->patchinfo->fudgeIV, lu->options.msgFile); } if ( lu->frontmtx->patchinfo->fudgeDV != NULL ) { ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n perturbations");CHKERRQ(ierr); DV_writeForHumanEye(lu->frontmtx->patchinfo->fudgeDV, lu->options.msgFile); } } PatchAndGoInfo_free(lu->frontmtx->patchinfo); } } /* post-process the factorization */ FrontMtx_postProcess(lu->frontmtx, lu->options.msglvl, lu->options.msgFile); if ( lu->options.msglvl > 2 ) { int err; ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n factor matrix after post-processing");CHKERRQ(ierr); FrontMtx_writeForHumanEye(lu->frontmtx, lu->options.msgFile); err = fflush(lu->options.msgFile); if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fflush() failed on file"); } lu->flg = SAME_NONZERO_PATTERN; lu->CleanUpSpooles = PETSC_TRUE; PetscFunctionReturn(0); }
PetscErrorCode MatSolve_SeqSpooles(Mat A,Vec b,Vec x) { Mat_Spooles *lu = (Mat_Spooles*)A->spptr; PetscScalar *array; DenseMtx *mtxY, *mtxX ; PetscErrorCode ierr; PetscInt irow,neqns=A->cmap->n,nrow=A->rmap->n,*iv; #if defined(PETSC_USE_COMPLEX) double x_real,x_imag; #else double *entX; #endif PetscFunctionBegin; mtxY = DenseMtx_new(); DenseMtx_init(mtxY, lu->options.typeflag, 0, 0, nrow, 1, 1, nrow); /* column major */ ierr = VecGetArray(b,&array);CHKERRQ(ierr); if (lu->options.useQR) { /* copy b to mtxY */ for ( irow = 0 ; irow < nrow; irow++ ) #if !defined(PETSC_USE_COMPLEX) DenseMtx_setRealEntry(mtxY, irow, 0, *array++); #else DenseMtx_setComplexEntry(mtxY, irow, 0, PetscRealPart(array[irow]), PetscImaginaryPart(array[irow])); #endif } else { /* copy permuted b to mtxY */ iv = IV_entries(lu->oldToNewIV); for ( irow = 0 ; irow < nrow; irow++ ) #if !defined(PETSC_USE_COMPLEX) DenseMtx_setRealEntry(mtxY, *iv++, 0, *array++); #else DenseMtx_setComplexEntry(mtxY,*iv++,0,PetscRealPart(array[irow]),PetscImaginaryPart(array[irow])); #endif } ierr = VecRestoreArray(b,&array);CHKERRQ(ierr); mtxX = DenseMtx_new(); DenseMtx_init(mtxX, lu->options.typeflag, 0, 0, neqns, 1, 1, neqns); if (lu->options.useQR) { FrontMtx_QR_solve(lu->frontmtx, lu->mtxA, mtxX, mtxY, lu->mtxmanager, lu->cpus, lu->options.msglvl, lu->options.msgFile); } else { FrontMtx_solve(lu->frontmtx, mtxX, mtxY, lu->mtxmanager, lu->cpus, lu->options.msglvl, lu->options.msgFile); } if ( lu->options.msglvl > 2 ) { int err; ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n right hand side matrix after permutation");CHKERRQ(ierr); DenseMtx_writeForHumanEye(mtxY, lu->options.msgFile); ierr = PetscFPrintf(PETSC_COMM_SELF,lu->options.msgFile, "\n\n solution matrix in new ordering");CHKERRQ(ierr); DenseMtx_writeForHumanEye(mtxX, lu->options.msgFile); err = fflush(lu->options.msgFile); if (err) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SYS,"fflush() failed on file"); } /* permute solution into original ordering, then copy to x */ DenseMtx_permuteRows(mtxX, lu->newToOldIV); ierr = VecGetArray(x,&array);CHKERRQ(ierr); #if !defined(PETSC_USE_COMPLEX) entX = DenseMtx_entries(mtxX); DVcopy(neqns, array, entX); #else for (irow=0; irow<nrow; irow++){ DenseMtx_complexEntry(mtxX,irow,0,&x_real,&x_imag); array[irow] = x_real+x_imag*PETSC_i; } #endif ierr = VecRestoreArray(x,&array);CHKERRQ(ierr); /* free memory */ DenseMtx_free(mtxX); DenseMtx_free(mtxY); PetscFunctionReturn(0); }
PetscErrorCode KSPView_PIPEFGMRES(KSP ksp,PetscViewer viewer) { KSP_PIPEFGMRES *pipefgmres = (KSP_PIPEFGMRES*)ksp->data; PetscErrorCode ierr; PetscBool iascii,isstring; PetscFunctionBegin; ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr); ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);CHKERRQ(ierr); if (iascii) { ierr = PetscViewerASCIIPrintf(viewer," restart=%D\n",pipefgmres->max_k);CHKERRQ(ierr); ierr = PetscViewerASCIIPrintf(viewer," happy breakdown tolerance %g\n",(double)pipefgmres->haptol);CHKERRQ(ierr); #if defined(PETSC_USE_COMPLEX) ierr = PetscViewerASCIIPrintf(viewer," shift=%g+%gi\n",PetscRealPart(pipefgmres->shift),PetscImaginaryPart(pipefgmres->shift));CHKERRQ(ierr); #else ierr = PetscViewerASCIIPrintf(viewer," shift=%g\n",pipefgmres->shift);CHKERRQ(ierr); #endif } else if (isstring) { ierr = PetscViewerStringSPrintf(viewer,"restart %D",pipefgmres->max_k);CHKERRQ(ierr); #if defined(PETSC_USE_COMPLEX) ierr = PetscViewerStringSPrintf(viewer," shift=%g+%gi\n",PetscRealPart(pipefgmres->shift),PetscImaginaryPart(pipefgmres->shift));CHKERRQ(ierr); #else ierr = PetscViewerStringSPrintf(viewer," shift=%g\n",pipefgmres->shift);CHKERRQ(ierr); #endif } PetscFunctionReturn(0); }
PetscErrorCode PFView_Constant(void *value,PetscViewer viewer) { PetscErrorCode ierr; PetscBool iascii; PetscFunctionBegin; ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr); if (iascii) { #if !defined(PETSC_USE_COMPLEX) ierr = PetscViewerASCIIPrintf(viewer,"Constant = %g\n",*(double*)value);CHKERRQ(ierr); #else ierr = PetscViewerASCIIPrintf(viewer,"Constant = %g + %gi\n",PetscRealPart(*(PetscScalar*)value),PetscImaginaryPart(*(PetscScalar*)value));CHKERRQ(ierr); #endif } PetscFunctionReturn(0); }
int main(int argc,char **args) { Mat C; Vec u,b; PetscErrorCode ierr; PetscMPIInt size,rank; PetscInt i,m = 5,N,start,end,M,idx[4]; PetscInt j,nrsub,ncsub,*rsub,*csub,mystart,myend; PetscBool flg; PetscScalar one = 1.0,Ke[16],*vals; PetscReal h,norm; ierr = PetscInitialize(&argc,&args,(char*)0,help);if (ierr) return ierr; ierr = PetscOptionsGetInt(NULL,NULL,"-m",&m,NULL);CHKERRQ(ierr); N = (m+1)*(m+1); /* dimension of matrix */ M = m*m; /* number of elements */ h = 1.0/m; /* mesh width */ ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr); ierr = MPI_Comm_size(PETSC_COMM_WORLD,&size);CHKERRQ(ierr); /* Create stiffness matrix */ ierr = MatCreate(PETSC_COMM_WORLD,&C);CHKERRQ(ierr); ierr = MatSetSizes(C,PETSC_DECIDE,PETSC_DECIDE,N,N);CHKERRQ(ierr); ierr = MatSetFromOptions(C);CHKERRQ(ierr); ierr = MatSetUp(C);CHKERRQ(ierr); start = rank*(M/size) + ((M%size) < rank ? (M%size) : rank); end = start + M/size + ((M%size) > rank); /* Form the element stiffness for the Laplacian */ ierr = FormElementStiffness(h*h,Ke);CHKERRQ(ierr); for (i=start; i<end; i++) { /* location of lower left corner of element */ /* node numbers for the four corners of element */ idx[0] = (m+1)*(i/m) + (i % m); idx[1] = idx[0]+1; idx[2] = idx[1] + m + 1; idx[3] = idx[2] - 1; ierr = MatSetValues(C,4,idx,4,idx,Ke,ADD_VALUES);CHKERRQ(ierr); } ierr = MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); /* Assemble the matrix again */ ierr = MatZeroEntries(C);CHKERRQ(ierr); for (i=start; i<end; i++) { /* location of lower left corner of element */ /* node numbers for the four corners of element */ idx[0] = (m+1)*(i/m) + (i % m); idx[1] = idx[0]+1; idx[2] = idx[1] + m + 1; idx[3] = idx[2] - 1; ierr = MatSetValues(C,4,idx,4,idx,Ke,ADD_VALUES);CHKERRQ(ierr); } ierr = MatAssemblyBegin(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(C,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); /* Create test vectors */ ierr = VecCreate(PETSC_COMM_WORLD,&u);CHKERRQ(ierr); ierr = VecSetSizes(u,PETSC_DECIDE,N);CHKERRQ(ierr); ierr = VecSetFromOptions(u);CHKERRQ(ierr); ierr = VecDuplicate(u,&b);CHKERRQ(ierr); ierr = VecSet(u,one);CHKERRQ(ierr); /* Check error */ ierr = MatMult(C,u,b);CHKERRQ(ierr); ierr = VecNorm(b,NORM_2,&norm);CHKERRQ(ierr); if (norm > PETSC_SQRT_MACHINE_EPSILON) { ierr = PetscPrintf(PETSC_COMM_WORLD,"Norm of error b %g should be near 0\n",(double)norm);CHKERRQ(ierr); } /* Now test MatGetValues() */ ierr = PetscOptionsHasName(NULL,NULL,"-get_values",&flg);CHKERRQ(ierr); if (flg) { ierr = MatGetOwnershipRange(C,&mystart,&myend);CHKERRQ(ierr); nrsub = myend - mystart; ncsub = 4; ierr = PetscMalloc1(nrsub*ncsub,&vals);CHKERRQ(ierr); ierr = PetscMalloc1(nrsub,&rsub);CHKERRQ(ierr); ierr = PetscMalloc1(ncsub,&csub);CHKERRQ(ierr); for (i=myend-1; i>=mystart; i--) rsub[myend-i-1] = i; for (i=0; i<ncsub; i++) csub[i] = 2*(ncsub-i) + mystart; ierr = MatGetValues(C,nrsub,rsub,ncsub,csub,vals);CHKERRQ(ierr); ierr = MatView(C,PETSC_VIEWER_STDOUT_WORLD);CHKERRQ(ierr); ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD,"processor number %d: start=%D, end=%D, mystart=%D, myend=%D\n",rank,start,end,mystart,myend);CHKERRQ(ierr); for (i=0; i<nrsub; i++) { for (j=0; j<ncsub; j++) { if (PetscImaginaryPart(vals[i*ncsub+j]) != 0.0) { ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD," C[%D, %D] = %g + %g i\n",rsub[i],csub[j],(double)PetscRealPart(vals[i*ncsub+j]),(double)PetscImaginaryPart(vals[i*ncsub+j]));CHKERRQ(ierr); } else { ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD," C[%D, %D] = %g\n",rsub[i],csub[j],(double)PetscRealPart(vals[i*ncsub+j]));CHKERRQ(ierr); } } } ierr = PetscSynchronizedFlush(PETSC_COMM_WORLD,PETSC_STDOUT);CHKERRQ(ierr); ierr = PetscFree(rsub);CHKERRQ(ierr); ierr = PetscFree(csub);CHKERRQ(ierr); ierr = PetscFree(vals);CHKERRQ(ierr); } /* Free data structures */ ierr = VecDestroy(&u);CHKERRQ(ierr); ierr = VecDestroy(&b);CHKERRQ(ierr); ierr = MatDestroy(&C);CHKERRQ(ierr); ierr = PetscFinalize(); return ierr; }
int main(int argc,char **argv) { int ierr; PetscScalar a; PetscInitialize(&argc,&argv,(char*)0,help); ierr = PetscOptionsGetScalar(NULL,"-a",&a,NULL);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_SELF,"Scalar a = %g + %gi\n",(double)PetscRealPart(a),(double)PetscImaginaryPart(a));CHKERRQ(ierr); ierr = PetscFinalize(); return 0; }
int main(int argc,char **argv) { Mat A[NMAT]; /* problem matrices */ FN f[NMAT]; /* functions to define the nonlinear operator */ NEP nep; /* nonlinear eigensolver context */ PetscInt n=20,Istart,Iend,i,nconv; PetscReal kappa=1.0,m=1.0,re,im,norm; PetscScalar kr,ki,sigma,numer[2],denom[2]; PetscErrorCode ierr; SlepcInitialize(&argc,&argv,(char*)0,help); ierr = PetscOptionsGetInt(NULL,"-n",&n,NULL);CHKERRQ(ierr); ierr = PetscOptionsGetReal(NULL,"-kappa",&kappa,NULL);CHKERRQ(ierr); ierr = PetscOptionsGetReal(NULL,"-mass",&m,NULL);CHKERRQ(ierr); sigma = kappa/m; ierr = PetscPrintf(PETSC_COMM_WORLD,"Loaded vibrating string, n=%D kappa=%g m=%g\n\n",n,(double)kappa,(double)m);CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Build the problem matrices - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* initialize matrices */ for (i=0;i<NMAT;i++) { ierr = MatCreate(PETSC_COMM_WORLD,&A[i]);CHKERRQ(ierr); ierr = MatSetSizes(A[i],PETSC_DECIDE,PETSC_DECIDE,n,n);CHKERRQ(ierr); ierr = MatSetFromOptions(A[i]);CHKERRQ(ierr); ierr = MatSetUp(A[i]);CHKERRQ(ierr); } ierr = MatGetOwnershipRange(A[0],&Istart,&Iend);CHKERRQ(ierr); /* A0 */ for (i=Istart;i<Iend;i++) { ierr = MatSetValue(A[0],i,i,(i==n-1)?1.0*n:2.0*n,INSERT_VALUES);CHKERRQ(ierr); if (i>0) { ierr = MatSetValue(A[0],i,i-1,-1.0*n,INSERT_VALUES);CHKERRQ(ierr); } if (i<n-1) { ierr = MatSetValue(A[0],i,i+1,-1.0*n,INSERT_VALUES);CHKERRQ(ierr); } } /* A1 */ for (i=Istart;i<Iend;i++) { ierr = MatSetValue(A[1],i,i,(i==n-1)?2.0/(6.0*n):4.0/(6.0*n),INSERT_VALUES);CHKERRQ(ierr); if (i>0) { ierr = MatSetValue(A[1],i,i-1,1.0/(6.0*n),INSERT_VALUES);CHKERRQ(ierr); } if (i<n-1) { ierr = MatSetValue(A[1],i,i+1,1.0/(6.0*n),INSERT_VALUES);CHKERRQ(ierr); } } /* A2 */ if (Istart<=n-1 && n-1<Iend) { ierr = MatSetValue(A[2],n-1,n-1,kappa,INSERT_VALUES); CHKERRQ(ierr); } /* assemble matrices */ for (i=0;i<NMAT;i++) { ierr = MatAssemblyBegin(A[i],MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); } for (i=0;i<NMAT;i++) { ierr = MatAssemblyEnd(A[i],MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create the problem functions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* f1=1 */ ierr = FNCreate(PETSC_COMM_WORLD,&f[0]);CHKERRQ(ierr); ierr = FNSetType(f[0],FNRATIONAL);CHKERRQ(ierr); numer[0] = 1.0; ierr = FNSetParameters(f[0],1,numer,0,NULL);CHKERRQ(ierr); /* f2=-lambda */ ierr = FNCreate(PETSC_COMM_WORLD,&f[1]);CHKERRQ(ierr); ierr = FNSetType(f[1],FNRATIONAL);CHKERRQ(ierr); numer[0] = -1.0; numer[1] = 0.0; ierr = FNSetParameters(f[1],2,numer,0,NULL);CHKERRQ(ierr); /* f3=lambda/(lambda-sigma) */ ierr = FNCreate(PETSC_COMM_WORLD,&f[2]);CHKERRQ(ierr); ierr = FNSetType(f[2],FNRATIONAL);CHKERRQ(ierr); numer[0] = 1.0; numer[1] = 0.0; denom[0] = 1.0; denom[1] = -sigma; ierr = FNSetParameters(f[2],2,numer,2,denom);CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create the eigensolver and solve the problem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ ierr = NEPCreate(PETSC_COMM_WORLD,&nep);CHKERRQ(ierr); ierr = NEPSetSplitOperator(nep,3,A,f,SUBSET_NONZERO_PATTERN);CHKERRQ(ierr); ierr = NEPSetFromOptions(nep);CHKERRQ(ierr); ierr = NEPSolve(nep);CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Display solution and clean up - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Get number of converged approximate eigenpairs */ ierr = NEPGetConverged(nep,&nconv);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD," Number of converged approximate eigenpairs: %D\n\n",nconv);CHKERRQ(ierr); if (nconv>0) { /* Display eigenvalues and relative errors */ ierr = PetscPrintf(PETSC_COMM_WORLD, " k ||T(k)x||\n" " ----------------- ------------------\n");CHKERRQ(ierr); for (i=0;i<nconv;i++) { ierr = NEPGetEigenpair(nep,i,&kr,&ki,NULL,NULL);CHKERRQ(ierr); ierr = NEPComputeRelativeError(nep,i,&norm);CHKERRQ(ierr); #if defined(PETSC_USE_COMPLEX) re = PetscRealPart(kr); im = PetscImaginaryPart(kr); #else re = kr; im = ki; #endif if (im!=0.0) { ierr = PetscPrintf(PETSC_COMM_WORLD," %9f%+9f j %12g\n",(double)re,(double)im,(double)norm);CHKERRQ(ierr); } else { ierr = PetscPrintf(PETSC_COMM_WORLD," %12f %12g\n",(double)re,(double)norm);CHKERRQ(ierr); } } ierr = PetscPrintf(PETSC_COMM_WORLD,"\n");CHKERRQ(ierr); } ierr = NEPDestroy(&nep);CHKERRQ(ierr); for (i=0;i<NMAT;i++) { ierr = MatDestroy(&A[i]);CHKERRQ(ierr); ierr = FNDestroy(&f[i]);CHKERRQ(ierr); } ierr = SlepcFinalize();CHKERRQ(ierr); return 0; }
int main(int argc,char **argv) { PetscErrorCode ierr; DS ds; FN f1,f2,f3,funs[3]; PetscScalar *Id,*A,*B,*wr,*wi,coeffs[2]; PetscReal tau=0.001,h,a=20,xi,re,im; PetscInt i,n=10,ld,nev; PetscViewer viewer; PetscBool verbose; SlepcInitialize(&argc,&argv,(char*)0,help); ierr = PetscOptionsGetInt(NULL,"-n",&n,NULL);CHKERRQ(ierr); ierr = PetscOptionsGetReal(NULL,"-tau",&tau,NULL);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD,"Solve a Dense System of type NEP - dimension %D, tau=%g.\n",n,(double)tau);CHKERRQ(ierr); ierr = PetscOptionsHasName(NULL,"-verbose",&verbose);CHKERRQ(ierr); /* Create DS object */ ierr = DSCreate(PETSC_COMM_WORLD,&ds);CHKERRQ(ierr); ierr = DSSetType(ds,DSNEP);CHKERRQ(ierr); ierr = DSSetFromOptions(ds);CHKERRQ(ierr); /* Set functions (prior to DSAllocate) */ ierr = FNCreate(PETSC_COMM_WORLD,&f1);CHKERRQ(ierr); ierr = FNSetType(f1,FNRATIONAL);CHKERRQ(ierr); coeffs[0] = -1.0; coeffs[1] = 0.0; ierr = FNSetParameters(f1,2,coeffs,0,NULL);CHKERRQ(ierr); ierr = FNCreate(PETSC_COMM_WORLD,&f2);CHKERRQ(ierr); ierr = FNSetType(f2,FNRATIONAL);CHKERRQ(ierr); coeffs[0] = 1.0; ierr = FNSetParameters(f2,1,coeffs,0,NULL);CHKERRQ(ierr); ierr = FNCreate(PETSC_COMM_WORLD,&f3);CHKERRQ(ierr); ierr = FNSetType(f3,FNEXP);CHKERRQ(ierr); coeffs[0] = -tau; ierr = FNSetParameters(f3,1,coeffs,0,NULL);CHKERRQ(ierr); funs[0] = f1; funs[1] = f2; funs[2] = f3; ierr = DSSetFN(ds,3,funs);CHKERRQ(ierr); /* Set dimensions */ ld = n+2; /* test leading dimension larger than n */ ierr = DSAllocate(ds,ld);CHKERRQ(ierr); ierr = DSSetDimensions(ds,n,0,0,0);CHKERRQ(ierr); /* Set up viewer */ ierr = PetscViewerASCIIGetStdout(PETSC_COMM_WORLD,&viewer);CHKERRQ(ierr); ierr = PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_INFO_DETAIL);CHKERRQ(ierr); ierr = DSView(ds,viewer);CHKERRQ(ierr); ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr); if (verbose) { ierr = PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB);CHKERRQ(ierr); } /* Fill matrices */ ierr = DSGetArray(ds,DS_MAT_E0,&Id);CHKERRQ(ierr); for (i=0;i<n;i++) Id[i+i*ld]=1.0; ierr = DSRestoreArray(ds,DS_MAT_E0,&Id);CHKERRQ(ierr); h = PETSC_PI/(PetscReal)(n+1); ierr = DSGetArray(ds,DS_MAT_E1,&A);CHKERRQ(ierr); for (i=0;i<n;i++) A[i+i*ld]=-2.0/(h*h)+a; for (i=1;i<n;i++) { A[i+(i-1)*ld]=1.0/(h*h); A[(i-1)+i*ld]=1.0/(h*h); } ierr = DSRestoreArray(ds,DS_MAT_E1,&A);CHKERRQ(ierr); ierr = DSGetArray(ds,DS_MAT_E2,&B);CHKERRQ(ierr); for (i=0;i<n;i++) { xi = (i+1)*h; B[i+i*ld] = -4.1+xi*(1.0-PetscExpReal(xi-PETSC_PI)); } ierr = DSRestoreArray(ds,DS_MAT_E2,&B);CHKERRQ(ierr); if (verbose) { ierr = PetscPrintf(PETSC_COMM_WORLD,"Initial - - - - - - - - -\n");CHKERRQ(ierr); ierr = DSView(ds,viewer);CHKERRQ(ierr); } /* Solve */ ierr = PetscMalloc2(n,&wr,n,&wi);CHKERRQ(ierr); ierr = DSSolve(ds,wr,wi);CHKERRQ(ierr); if (verbose) { ierr = PetscPrintf(PETSC_COMM_WORLD,"After solve - - - - - - - - -\n");CHKERRQ(ierr); ierr = DSView(ds,viewer);CHKERRQ(ierr); } /* Print first eigenvalue */ ierr = PetscPrintf(PETSC_COMM_WORLD,"Computed eigenvalue =\n",n);CHKERRQ(ierr); nev = 1; for (i=0;i<nev;i++) { #if defined(PETSC_USE_COMPLEX) re = PetscRealPart(wr[i]); im = PetscImaginaryPart(wr[i]); #else re = wr[i]; im = wi[i]; #endif if (PetscAbs(im)<1e-10) { ierr = PetscViewerASCIIPrintf(viewer," %.5f\n",(double)re);CHKERRQ(ierr); } else { ierr = PetscViewerASCIIPrintf(viewer," %.5f%+.5fi\n",(double)re,(double)im);CHKERRQ(ierr); } } ierr = PetscFree2(wr,wi);CHKERRQ(ierr); ierr = FNDestroy(&f1);CHKERRQ(ierr); ierr = FNDestroy(&f2);CHKERRQ(ierr); ierr = FNDestroy(&f3);CHKERRQ(ierr); ierr = DSDestroy(&ds);CHKERRQ(ierr); ierr = SlepcFinalize(); return 0; }
/*@ EPSSolve - Solves the eigensystem. Collective on EPS Input Parameter: . eps - eigensolver context obtained from EPSCreate() Options Database Keys: + -eps_view - print information about the solver used . -eps_view_mat0 binary - save the first matrix (A) to the default binary viewer . -eps_view_mat1 binary - save the second matrix (B) to the default binary viewer - -eps_plot_eigs - plot computed eigenvalues Level: beginner .seealso: EPSCreate(), EPSSetUp(), EPSDestroy(), EPSSetTolerances() @*/ PetscErrorCode EPSSolve(EPS eps) { PetscErrorCode ierr; PetscInt i,nmat; PetscReal re,im; PetscScalar dot; PetscBool flg,iscayley; PetscViewer viewer; PetscViewerFormat format; PetscDraw draw; PetscDrawSP drawsp; STMatMode matmode; Mat A,B; Vec w,x; PetscFunctionBegin; PetscValidHeaderSpecific(eps,EPS_CLASSID,1); ierr = PetscLogEventBegin(EPS_Solve,eps,0,0,0);CHKERRQ(ierr); /* call setup */ ierr = EPSSetUp(eps);CHKERRQ(ierr); eps->nconv = 0; eps->its = 0; for (i=0;i<eps->ncv;i++) { eps->eigr[i] = 0.0; eps->eigi[i] = 0.0; eps->errest[i] = 0.0; } ierr = EPSMonitor(eps,eps->its,eps->nconv,eps->eigr,eps->eigi,eps->errest,eps->ncv);CHKERRQ(ierr); /* call solver */ ierr = (*eps->ops->solve)(eps);CHKERRQ(ierr); eps->state = EPS_STATE_SOLVED; ierr = STGetMatMode(eps->st,&matmode);CHKERRQ(ierr); if (matmode == ST_MATMODE_INPLACE && eps->ispositive) { /* Purify eigenvectors before reverting operator */ ierr = EPSComputeVectors(eps);CHKERRQ(ierr); } ierr = STPostSolve(eps->st);CHKERRQ(ierr); if (!eps->reason) SETERRQ(PetscObjectComm((PetscObject)eps),PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason"); /* Map eigenvalues back to the original problem, necessary in some * spectral transformations */ if (eps->ops->backtransform) { ierr = (*eps->ops->backtransform)(eps);CHKERRQ(ierr); } #if !defined(PETSC_USE_COMPLEX) /* reorder conjugate eigenvalues (positive imaginary first) */ for (i=0; i<eps->nconv-1; i++) { if (eps->eigi[i] != 0) { if (eps->eigi[i] < 0) { eps->eigi[i] = -eps->eigi[i]; eps->eigi[i+1] = -eps->eigi[i+1]; /* the next correction only works with eigenvectors */ ierr = EPSComputeVectors(eps);CHKERRQ(ierr); ierr = BVScaleColumn(eps->V,i+1,-1.0);CHKERRQ(ierr); } i++; } } #endif ierr = STGetNumMatrices(eps->st,&nmat);CHKERRQ(ierr); ierr = STGetOperators(eps->st,0,&A);CHKERRQ(ierr); if (nmat>1) { ierr = STGetOperators(eps->st,1,&B);CHKERRQ(ierr); } /* In the case of Cayley transform, eigenvectors need to be B-normalized */ ierr = PetscObjectTypeCompare((PetscObject)eps->st,STCAYLEY,&iscayley);CHKERRQ(ierr); if (iscayley && eps->isgeneralized && eps->ishermitian) { ierr = MatGetVecs(B,NULL,&w);CHKERRQ(ierr); ierr = EPSComputeVectors(eps);CHKERRQ(ierr); for (i=0;i<eps->nconv;i++) { ierr = BVGetColumn(eps->V,i,&x);CHKERRQ(ierr); ierr = MatMult(B,x,w);CHKERRQ(ierr); ierr = VecDot(w,x,&dot);CHKERRQ(ierr); ierr = VecScale(x,1.0/PetscSqrtScalar(dot));CHKERRQ(ierr); ierr = BVRestoreColumn(eps->V,i,&x);CHKERRQ(ierr); } ierr = VecDestroy(&w);CHKERRQ(ierr); } /* sort eigenvalues according to eps->which parameter */ ierr = SlepcSortEigenvalues(eps->sc,eps->nconv,eps->eigr,eps->eigi,eps->perm);CHKERRQ(ierr); ierr = PetscLogEventEnd(EPS_Solve,eps,0,0,0);CHKERRQ(ierr); /* various viewers */ ierr = MatViewFromOptions(A,((PetscObject)eps)->prefix,"-eps_view_mat0");CHKERRQ(ierr); if (nmat>1) { ierr = MatViewFromOptions(B,((PetscObject)eps)->prefix,"-eps_view_mat1");CHKERRQ(ierr); } ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)eps),((PetscObject)eps)->prefix,"-eps_view",&viewer,&format,&flg);CHKERRQ(ierr); if (flg && !PetscPreLoadingOn) { ierr = PetscViewerPushFormat(viewer,format);CHKERRQ(ierr); ierr = EPSView(eps,viewer);CHKERRQ(ierr); ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); } flg = PETSC_FALSE; ierr = PetscOptionsGetBool(((PetscObject)eps)->prefix,"-eps_plot_eigs",&flg,NULL);CHKERRQ(ierr); if (flg) { ierr = PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,300,300,&viewer);CHKERRQ(ierr); ierr = PetscViewerDrawGetDraw(viewer,0,&draw);CHKERRQ(ierr); ierr = PetscDrawSPCreate(draw,1,&drawsp);CHKERRQ(ierr); for (i=0;i<eps->nconv;i++) { #if defined(PETSC_USE_COMPLEX) re = PetscRealPart(eps->eigr[i]); im = PetscImaginaryPart(eps->eigi[i]); #else re = eps->eigr[i]; im = eps->eigi[i]; #endif ierr = PetscDrawSPAddPoint(drawsp,&re,&im);CHKERRQ(ierr); } ierr = PetscDrawSPDraw(drawsp,PETSC_TRUE);CHKERRQ(ierr); ierr = PetscDrawSPDestroy(&drawsp);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); } /* Remove deflation and initial subspaces */ eps->nds = 0; eps->nini = 0; PetscFunctionReturn(0); }
int main(int argc,char **args) { Vec x,b,u; /* approx solution, RHS, exact solution */ Mat A; /* linear system matrix */ KSP ksp; /* linear solver context */ PetscReal norm; /* norm of solution error */ PetscInt dim,i,j,Ii,J,Istart,Iend,n = 6,its,use_random; PetscErrorCode ierr; PetscScalar v,none = -1.0,sigma2,pfive = 0.5,*xa; PetscRandom rctx; PetscReal h2,sigma1 = 100.0; PetscBool flg = PETSC_FALSE; PetscScalar a = 1.0+PETSC_i; PetscInitialize(&argc,&args,(char*)0,help); #if !defined(PETSC_USE_COMPLEX) SETERRQ(PETSC_COMM_WORLD,1,"This example requires complex numbers"); #endif a=1.0+PETSC_i; printf("%g+%gi\n",(double)PetscRealPart(a),(double)PetscImaginaryPart(a)); ierr = PetscOptionsGetReal(NULL,"-sigma1",&sigma1,NULL);CHKERRQ(ierr); ierr = PetscOptionsGetInt(NULL,"-n",&n,NULL);CHKERRQ(ierr); dim = n*n; /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Compute the matrix and right-hand-side vector that define the linear system, Ax = b. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Create parallel matrix, specifying only its global dimensions. When using MatCreate(), the matrix format can be specified at runtime. Also, the parallel partitioning of the matrix is determined by PETSc at runtime. */ ierr = MatCreate(PETSC_COMM_WORLD,&A);CHKERRQ(ierr); ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,dim,dim);CHKERRQ(ierr); ierr = MatSetFromOptions(A);CHKERRQ(ierr); ierr = MatSetUp(A);CHKERRQ(ierr); /* Currently, all PETSc parallel matrix formats are partitioned by contiguous chunks of rows across the processors. Determine which rows of the matrix are locally owned. */ ierr = MatGetOwnershipRange(A,&Istart,&Iend);CHKERRQ(ierr); /* Set matrix elements in parallel. - Each processor needs to insert only elements that it owns locally (but any non-local elements will be sent to the appropriate processor during matrix assembly). - Always specify global rows and columns of matrix entries. */ ierr = PetscOptionsGetBool(NULL,"-norandom",&flg,NULL);CHKERRQ(ierr); if (flg) use_random = 0; else use_random = 1; if (use_random) { ierr = PetscRandomCreate(PETSC_COMM_WORLD,&rctx);CHKERRQ(ierr); ierr = PetscRandomSetFromOptions(rctx);CHKERRQ(ierr); ierr = PetscRandomSetInterval(rctx,0.0,PETSC_i);CHKERRQ(ierr); } else { sigma2 = 10.0*PETSC_i; } h2 = 1.0/((n+1)*(n+1)); for (Ii=Istart; Ii<Iend; Ii++) { v = -1.0; i = Ii/n; j = Ii - i*n; if (i>0) { J = Ii-n; ierr = MatSetValues(A,1,&Ii,1,&J,&v,ADD_VALUES);CHKERRQ(ierr); } if (i<n-1) { J = Ii+n; ierr = MatSetValues(A,1,&Ii,1,&J,&v,ADD_VALUES);CHKERRQ(ierr); } if (j>0) { J = Ii-1; ierr = MatSetValues(A,1,&Ii,1,&J,&v,ADD_VALUES);CHKERRQ(ierr); } if (j<n-1) { J = Ii+1; ierr = MatSetValues(A,1,&Ii,1,&J,&v,ADD_VALUES);CHKERRQ(ierr); } if (use_random) {ierr = PetscRandomGetValue(rctx,&sigma2);CHKERRQ(ierr);} v = 4.0 - sigma1*h2 + sigma2*h2; ierr = MatSetValues(A,1,&Ii,1,&Ii,&v,ADD_VALUES);CHKERRQ(ierr); } if (use_random) {ierr = PetscRandomDestroy(&rctx);CHKERRQ(ierr);} /* Assemble matrix, using the 2-step process: MatAssemblyBegin(), MatAssemblyEnd() Computations can be done while messages are in transition by placing code between these two statements. */ ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr); /* Create parallel vectors. - When using VecCreate(), VecSetSizes() and VecSetFromOptions(), we specify only the vector's global dimension; the parallel partitioning is determined at runtime. - Note: We form 1 vector from scratch and then duplicate as needed. */ ierr = VecCreate(PETSC_COMM_WORLD,&u);CHKERRQ(ierr); ierr = VecSetSizes(u,PETSC_DECIDE,dim);CHKERRQ(ierr); ierr = VecSetFromOptions(u);CHKERRQ(ierr); ierr = VecDuplicate(u,&b);CHKERRQ(ierr); ierr = VecDuplicate(b,&x);CHKERRQ(ierr); /* Set exact solution; then compute right-hand-side vector. */ if (use_random) { ierr = PetscRandomCreate(PETSC_COMM_WORLD,&rctx);CHKERRQ(ierr); ierr = PetscRandomSetFromOptions(rctx);CHKERRQ(ierr); ierr = VecSetRandom(u,rctx);CHKERRQ(ierr); } else { ierr = VecSet(u,pfive);CHKERRQ(ierr); } ierr = MatMult(A,u,b);CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Create the linear solver and set various options - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Create linear solver context */ ierr = KSPCreate(PETSC_COMM_WORLD,&ksp);CHKERRQ(ierr); /* Set operators. Here the matrix that defines the linear system also serves as the preconditioning matrix. */ ierr = KSPSetOperators(ksp,A,A);CHKERRQ(ierr); /* Set runtime options, e.g., -ksp_type <type> -pc_type <type> -ksp_monitor -ksp_rtol <rtol> */ ierr = KSPSetFromOptions(ksp);CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Solve the linear system - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ ierr = KSPSolve(ksp,b,x);CHKERRQ(ierr); /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Check solution and clean up - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Print the first 3 entries of x; this demonstrates extraction of the real and imaginary components of the complex vector, x. */ flg = PETSC_FALSE; ierr = PetscOptionsGetBool(NULL,"-print_x3",&flg,NULL);CHKERRQ(ierr); if (flg) { ierr = VecGetArray(x,&xa);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD,"The first three entries of x are:\n");CHKERRQ(ierr); for (i=0; i<3; i++) { ierr = PetscPrintf(PETSC_COMM_WORLD,"x[%D] = %g + %g i\n",i,(double)PetscRealPart(xa[i]),(double)PetscImaginaryPart(xa[i]));CHKERRQ(ierr); } ierr = VecRestoreArray(x,&xa);CHKERRQ(ierr); } /* Check the error */ ierr = VecAXPY(x,none,u);CHKERRQ(ierr); ierr = VecNorm(x,NORM_2,&norm);CHKERRQ(ierr); ierr = KSPGetIterationNumber(ksp,&its);CHKERRQ(ierr); ierr = PetscPrintf(PETSC_COMM_WORLD,"Norm of error %g iterations %D\n",(double)norm,its);CHKERRQ(ierr); /* Free work space. All PETSc objects should be destroyed when they are no longer needed. */ ierr = KSPDestroy(&ksp);CHKERRQ(ierr); if (use_random) {ierr = PetscRandomDestroy(&rctx);CHKERRQ(ierr);} ierr = VecDestroy(&u);CHKERRQ(ierr); ierr = VecDestroy(&x);CHKERRQ(ierr); ierr = VecDestroy(&b);CHKERRQ(ierr); ierr = MatDestroy(&A);CHKERRQ(ierr); ierr = PetscFinalize(); return 0; }
/*@ PEPSolve - Solves the polynomial eigensystem. Collective on PEP Input Parameter: . pep - eigensolver context obtained from PEPCreate() Options Database Keys: + -pep_view - print information about the solver used - -pep_plot_eigs - plot computed eigenvalues Level: beginner .seealso: PEPCreate(), PEPSetUp(), PEPDestroy(), PEPSetTolerances() @*/ PetscErrorCode PEPSolve(PEP pep) { PetscErrorCode ierr; PetscInt i; PetscReal re,im; PetscBool flg,islinear; PetscViewer viewer; PetscViewerFormat format; PetscDraw draw; PetscDrawSP drawsp; PetscFunctionBegin; PetscValidHeaderSpecific(pep,PEP_CLASSID,1); ierr = PetscLogEventBegin(PEP_Solve,pep,0,0,0);CHKERRQ(ierr); /* call setup */ ierr = PEPSetUp(pep);CHKERRQ(ierr); pep->nconv = 0; pep->its = 0; for (i=0;i<pep->ncv;i++) { pep->eigr[i] = 0.0; pep->eigi[i] = 0.0; pep->errest[i] = 0.0; } ierr = PEPMonitor(pep,pep->its,pep->nconv,pep->eigr,pep->eigi,pep->errest,pep->ncv);CHKERRQ(ierr); ierr = (*pep->ops->solve)(pep);CHKERRQ(ierr); ierr = PetscObjectTypeCompare((PetscObject)pep,PEPLINEAR,&islinear);CHKERRQ(ierr); if (!islinear) { ierr = STPostSolve(pep->st);CHKERRQ(ierr); } if (!pep->reason) SETERRQ(PetscObjectComm((PetscObject)pep),PETSC_ERR_PLIB,"Internal error, solver returned without setting converged reason"); if (!islinear) { /* Map eigenvalues back to the original problem */ ierr = STGetTransform(pep->st,&flg);CHKERRQ(ierr); if (flg) { ierr = STBackTransform(pep->st,pep->nconv,pep->eigr,pep->eigi);CHKERRQ(ierr); } } pep->state = PEP_STATE_SOLVED; if (pep->refine==PEP_REFINE_SIMPLE && pep->rits>0) { ierr = PEPComputeVectors(pep);CHKERRQ(ierr); ierr = PEPNewtonRefinementSimple(pep,&pep->rits,&pep->rtol,pep->nconv);CHKERRQ(ierr); pep->state = PEP_STATE_EIGENVECTORS; } #if !defined(PETSC_USE_COMPLEX) /* reorder conjugate eigenvalues (positive imaginary first) */ for (i=0;i<pep->nconv-1;i++) { if (pep->eigi[i] != 0) { if (pep->eigi[i] < 0) { pep->eigi[i] = -pep->eigi[i]; pep->eigi[i+1] = -pep->eigi[i+1]; /* the next correction only works with eigenvectors */ ierr = PEPComputeVectors(pep);CHKERRQ(ierr); ierr = BVScaleColumn(pep->V,i+1,-1.0);CHKERRQ(ierr); } i++; } } #endif /* sort eigenvalues according to pep->which parameter */ ierr = SlepcSortEigenvalues(pep->sc,pep->nconv,pep->eigr,pep->eigi,pep->perm);CHKERRQ(ierr); ierr = PetscLogEventEnd(PEP_Solve,pep,0,0,0);CHKERRQ(ierr); /* various viewers */ ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)pep),((PetscObject)pep)->prefix,"-pep_view",&viewer,&format,&flg);CHKERRQ(ierr); if (flg && !PetscPreLoadingOn) { ierr = PetscViewerPushFormat(viewer,format);CHKERRQ(ierr); ierr = PEPView(pep,viewer);CHKERRQ(ierr); ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); } flg = PETSC_FALSE; ierr = PetscOptionsGetBool(((PetscObject)pep)->prefix,"-pep_plot_eigs",&flg,NULL);CHKERRQ(ierr); if (flg) { ierr = PetscViewerDrawOpen(PETSC_COMM_SELF,0,"Computed Eigenvalues",PETSC_DECIDE,PETSC_DECIDE,300,300,&viewer);CHKERRQ(ierr); ierr = PetscViewerDrawGetDraw(viewer,0,&draw);CHKERRQ(ierr); ierr = PetscDrawSPCreate(draw,1,&drawsp);CHKERRQ(ierr); for (i=0;i<pep->nconv;i++) { #if defined(PETSC_USE_COMPLEX) re = PetscRealPart(pep->eigr[i]); im = PetscImaginaryPart(pep->eigi[i]); #else re = pep->eigr[i]; im = pep->eigi[i]; #endif ierr = PetscDrawSPAddPoint(drawsp,&re,&im);CHKERRQ(ierr); } ierr = PetscDrawSPDraw(drawsp,PETSC_TRUE);CHKERRQ(ierr); ierr = PetscDrawSPDestroy(&drawsp);CHKERRQ(ierr); ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr); } /* Remove the initial subspace */ pep->nini = 0; PetscFunctionReturn(0); }