1 // Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at 2 // the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights 3 // reserved. See files LICENSE and NOTICE for details. 4 // 5 // This file is part of CEED, a collection of benchmarks, miniapps, software 6 // libraries and APIs for efficient high-order finite element and spectral 7 // element discretizations for exascale applications. For more information and 8 // source code availability see http://github.com/ceed. 9 // 10 // The CEED research is supported by the Exascale Computing Project 17-SC-20-SC, 11 // a collaborative effort of two U.S. Department of Energy organizations (Office 12 // of Science and the National Nuclear Security Administration) responsible for 13 // the planning and preparation of a capable exascale ecosystem, including 14 // software, applications, hardware, advanced system engineering and early 15 // testbed platforms, in support of the nation's exascale computing imperative. 16 17 // libCEED + PETSc Example: Navier-Stokes 18 // 19 // This example demonstrates a simple usage of libCEED with PETSc to solve a 20 // Navier-Stokes problem. 21 // 22 // The code is intentionally "raw", using only low-level communication 23 // primitives. 24 // 25 // Build with: 26 // 27 // make [PETSC_DIR=</path/to/petsc>] [CEED_DIR=</path/to/libceed>] navierstokes 28 // 29 // Sample runs: 30 // 31 // ./navierstokes -ceed /cpu/self -problem density_current -degree 1 32 // ./navierstokes -ceed /gpu/occa -problem advection -degree 1 33 // 34 //TESTARGS -ceed {ceed_resource} -test -degree 1 35 36 /// @file 37 /// Navier-Stokes example using PETSc 38 39 const char help[] = "Solve Navier-Stokes using PETSc and libCEED\n"; 40 41 #include <petscts.h> 42 #include <petscdmplex.h> 43 #include <ceed.h> 44 #include <stdbool.h> 45 #include <petscsys.h> 46 #include "common.h" 47 #include "advection.h" 48 #include "advection2d.h" 49 #include "densitycurrent.h" 50 51 // Problem Options 52 typedef enum { 53 NS_DENSITY_CURRENT = 0, 54 NS_ADVECTION = 1, 55 NS_ADVECTION2D = 2, 56 } problemType; 57 static const char *const problemTypes[] = { 58 "density_current", 59 "advection", 60 "advection2d", 61 "problemType","NS_",0 62 }; 63 64 typedef enum { 65 STAB_NONE = 0, 66 STAB_SU = 1, // Streamline Upwind 67 STAB_SUPG = 2, // Streamline Upwind Petrov-Galerkin 68 } StabilizationType; 69 static const char *const StabilizationTypes[] = { 70 "NONE", 71 "SU", 72 "SUPG", 73 "StabilizationType", "STAB_", NULL 74 }; 75 76 // Problem specific data 77 typedef struct { 78 CeedInt dim, qdatasize; 79 CeedQFunctionUser setup, ics, apply_rhs, apply_ifunction; 80 PetscErrorCode (*bc)(PetscInt, PetscReal, const PetscReal[], PetscInt, 81 PetscScalar[], void *); 82 const char *setup_loc, *ics_loc, *apply_rhs_loc, *apply_ifunction_loc; 83 const bool non_zero_time; 84 } problemData; 85 86 problemData problemOptions[] = { 87 [NS_DENSITY_CURRENT] = { 88 .dim = 3, 89 .qdatasize = 10, 90 .setup = Setup, 91 .setup_loc = Setup_loc, 92 .ics = ICsDC, 93 .ics_loc = ICsDC_loc, 94 .apply_rhs = DC, 95 .apply_rhs_loc = DC_loc, 96 .apply_ifunction = IFunction_DC, 97 .apply_ifunction_loc = IFunction_DC_loc, 98 .bc = Exact_DC, 99 .non_zero_time = false, 100 }, 101 [NS_ADVECTION] = { 102 .dim = 3, 103 .qdatasize = 10, 104 .setup = Setup, 105 .setup_loc = Setup_loc, 106 .ics = ICsAdvection, 107 .ics_loc = ICsAdvection_loc, 108 .apply_rhs = Advection, 109 .apply_rhs_loc = Advection_loc, 110 .apply_ifunction = IFunction_Advection, 111 .apply_ifunction_loc = IFunction_Advection_loc, 112 .bc = Exact_Advection, 113 .non_zero_time = true, 114 }, 115 [NS_ADVECTION2D] = { 116 .dim = 2, 117 .qdatasize = 5, 118 .setup = Setup2d, 119 .setup_loc = Setup2d_loc, 120 .ics = ICsAdvection2d, 121 .ics_loc = ICsAdvection2d_loc, 122 .apply_rhs = Advection2d, 123 .apply_rhs_loc = Advection2d_loc, 124 .apply_ifunction = IFunction_Advection2d, 125 .apply_ifunction_loc = IFunction_Advection2d_loc, 126 .bc = Exact_Advection2d, 127 .non_zero_time = true, 128 }, 129 }; 130 131 // PETSc user data 132 typedef struct User_ *User; 133 typedef struct Units_ *Units; 134 135 struct User_ { 136 MPI_Comm comm; 137 PetscInt outputfreq; 138 DM dm; 139 DM dmviz; 140 Mat interpviz; 141 Ceed ceed; 142 Units units; 143 CeedVector qceed, qdotceed, gceed; 144 CeedOperator op_rhs, op_ifunction; 145 Vec M; 146 char outputfolder[PETSC_MAX_PATH_LEN]; 147 PetscInt contsteps; 148 }; 149 150 struct Units_ { 151 // fundamental units 152 PetscScalar meter; 153 PetscScalar kilogram; 154 PetscScalar second; 155 PetscScalar Kelvin; 156 // derived units 157 PetscScalar Pascal; 158 PetscScalar JperkgK; 159 PetscScalar mpersquareds; 160 PetscScalar WpermK; 161 PetscScalar kgpercubicm; 162 PetscScalar kgpersquaredms; 163 PetscScalar Joulepercubicm; 164 }; 165 166 typedef struct SimpleBC_ *SimpleBC; 167 struct SimpleBC_ { 168 PetscInt nwall, nslip[3]; 169 PetscInt walls[10], slips[3][10]; 170 }; 171 172 // Essential BC dofs are encoded in closure indices as -(i+1). 173 static PetscInt Involute(PetscInt i) { 174 return i >= 0 ? i : -(i+1); 175 } 176 177 // Utility function to create local CEED restriction 178 static PetscErrorCode CreateRestrictionFromPlex(Ceed ceed, DM dm, CeedInt P, 179 CeedElemRestriction *Erestrict) { 180 181 PetscSection section; 182 PetscInt c, cStart, cEnd, Nelem, Ndof, *erestrict, eoffset, nfields, dim; 183 PetscErrorCode ierr; 184 Vec Uloc; 185 186 PetscFunctionBeginUser; 187 ierr = DMGetDimension(dm, &dim); CHKERRQ(ierr); 188 ierr = DMGetLocalSection(dm,§ion); CHKERRQ(ierr); 189 ierr = PetscSectionGetNumFields(section, &nfields); CHKERRQ(ierr); 190 PetscInt ncomp[nfields], fieldoff[nfields+1]; 191 fieldoff[0] = 0; 192 for (PetscInt f=0; f<nfields; f++) { 193 ierr = PetscSectionGetFieldComponents(section, f, &ncomp[f]); CHKERRQ(ierr); 194 fieldoff[f+1] = fieldoff[f] + ncomp[f]; 195 } 196 197 ierr = DMPlexGetHeightStratum(dm,0,&cStart,&cEnd); CHKERRQ(ierr); 198 Nelem = cEnd - cStart; 199 ierr = PetscMalloc1(Nelem*PetscPowInt(P, dim), &erestrict); CHKERRQ(ierr); 200 for (c=cStart,eoffset=0; c<cEnd; c++) { 201 PetscInt numindices, *indices, nnodes; 202 ierr = DMPlexGetClosureIndices(dm, section, section, c, &numindices, 203 &indices, NULL); CHKERRQ(ierr); 204 if (numindices % fieldoff[nfields]) SETERRQ1(PETSC_COMM_SELF, 205 PETSC_ERR_ARG_INCOMP, "Number of closure indices not compatible with Cell %D", 206 c); 207 nnodes = numindices / fieldoff[nfields]; 208 for (PetscInt i=0; i<nnodes; i++) { 209 // Check that indices are blocked by node and thus can be coalesced as a single field with 210 // fieldoff[nfields] = sum(ncomp) components. 211 for (PetscInt f=0; f<nfields; f++) { 212 for (PetscInt j=0; j<ncomp[f]; j++) { 213 if (Involute(indices[fieldoff[f]*nnodes + i*ncomp[f] + j]) 214 != Involute(indices[i*ncomp[0]]) + fieldoff[f] + j) 215 SETERRQ4(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP, 216 "Cell %D closure indices not interlaced for node %D field %D component %D", 217 c, i, f, j); 218 } 219 } 220 // Essential boundary conditions are encoded as -(loc+1), but we don't care so we decode. 221 PetscInt loc = Involute(indices[i*ncomp[0]]); 222 erestrict[eoffset++] = loc; 223 } 224 ierr = DMPlexRestoreClosureIndices(dm, section, section, c, &numindices, 225 &indices, NULL); CHKERRQ(ierr); 226 } 227 if (eoffset != Nelem*PetscPowInt(P, dim)) SETERRQ3(PETSC_COMM_SELF, 228 PETSC_ERR_LIB,"ElemRestriction of size (%D,%D) initialized %D nodes", Nelem, 229 PetscPowInt(P, dim),eoffset); 230 ierr = DMGetLocalVector(dm, &Uloc); CHKERRQ(ierr); 231 ierr = VecGetLocalSize(Uloc, &Ndof); CHKERRQ(ierr); 232 ierr = DMRestoreLocalVector(dm, &Uloc); CHKERRQ(ierr); 233 CeedElemRestrictionCreate(ceed, Nelem, PetscPowInt(P, dim), fieldoff[nfields], 234 1, Ndof, CEED_MEM_HOST, CEED_COPY_VALUES, erestrict, 235 Erestrict); 236 ierr = PetscFree(erestrict); CHKERRQ(ierr); 237 PetscFunctionReturn(0); 238 } 239 240 static int CreateVectorFromPetscVec(Ceed ceed, Vec p, CeedVector *v) { 241 PetscErrorCode ierr; 242 PetscInt m; 243 244 PetscFunctionBeginUser; 245 ierr = VecGetLocalSize(p, &m); CHKERRQ(ierr); 246 ierr = CeedVectorCreate(ceed, m, v); CHKERRQ(ierr); 247 PetscFunctionReturn(0); 248 } 249 250 static int VectorPlacePetscVec(CeedVector c, Vec p) { 251 PetscErrorCode ierr; 252 PetscInt mceed,mpetsc; 253 PetscScalar *a; 254 255 PetscFunctionBeginUser; 256 ierr = CeedVectorGetLength(c, &mceed); CHKERRQ(ierr); 257 ierr = VecGetLocalSize(p, &mpetsc); CHKERRQ(ierr); 258 if (mceed != mpetsc) SETERRQ2(PETSC_COMM_SELF,PETSC_ERR_ARG_INCOMP, 259 "Cannot place PETSc Vec of length %D in CeedVector of length %D",mpetsc,mceed); 260 ierr = VecGetArray(p, &a); CHKERRQ(ierr); 261 CeedVectorSetArray(c, CEED_MEM_HOST, CEED_USE_POINTER, a); 262 PetscFunctionReturn(0); 263 } 264 265 static PetscErrorCode DMPlexInsertBoundaryValues_NS(DM dm, 266 PetscBool insertEssential, Vec Qloc, PetscReal time, Vec faceGeomFVM, 267 Vec cellGeomFVM, Vec gradFVM) { 268 PetscErrorCode ierr; 269 Vec Qbc; 270 271 PetscFunctionBegin; 272 ierr = DMGetNamedLocalVector(dm, "Qbc", &Qbc); CHKERRQ(ierr); 273 ierr = VecAXPY(Qloc, 1., Qbc); CHKERRQ(ierr); 274 ierr = DMRestoreNamedLocalVector(dm, "Qbc", &Qbc); CHKERRQ(ierr); 275 PetscFunctionReturn(0); 276 } 277 278 // This is the RHS of the ODE, given as u_t = G(t,u) 279 // This function takes in a state vector Q and writes into G 280 static PetscErrorCode RHS_NS(TS ts, PetscReal t, Vec Q, Vec G, void *userData) { 281 PetscErrorCode ierr; 282 User user = *(User *)userData; 283 PetscScalar *q, *g; 284 Vec Qloc, Gloc; 285 286 // Global-to-local 287 PetscFunctionBeginUser; 288 ierr = DMGetLocalVector(user->dm, &Qloc); CHKERRQ(ierr); 289 ierr = DMGetLocalVector(user->dm, &Gloc); CHKERRQ(ierr); 290 ierr = VecZeroEntries(Qloc); CHKERRQ(ierr); 291 ierr = DMGlobalToLocal(user->dm, Q, INSERT_VALUES, Qloc); CHKERRQ(ierr); 292 ierr = DMPlexInsertBoundaryValues(user->dm, PETSC_TRUE, Qloc, 0.0, 293 NULL, NULL, NULL); CHKERRQ(ierr); 294 ierr = VecZeroEntries(Gloc); CHKERRQ(ierr); 295 296 // Ceed Vectors 297 ierr = VecGetArrayRead(Qloc, (const PetscScalar **)&q); CHKERRQ(ierr); 298 ierr = VecGetArray(Gloc, &g); CHKERRQ(ierr); 299 CeedVectorSetArray(user->qceed, CEED_MEM_HOST, CEED_USE_POINTER, q); 300 CeedVectorSetArray(user->gceed, CEED_MEM_HOST, CEED_USE_POINTER, g); 301 302 // Apply CEED operator 303 CeedOperatorApply(user->op_rhs, user->qceed, user->gceed, 304 CEED_REQUEST_IMMEDIATE); 305 306 // Restore vectors 307 ierr = VecRestoreArrayRead(Qloc, (const PetscScalar **)&q); CHKERRQ(ierr); 308 ierr = VecRestoreArray(Gloc, &g); CHKERRQ(ierr); 309 310 ierr = VecZeroEntries(G); CHKERRQ(ierr); 311 ierr = DMLocalToGlobal(user->dm, Gloc, ADD_VALUES, G); CHKERRQ(ierr); 312 313 // Inverse of the lumped mass matrix 314 ierr = VecPointwiseMult(G, G, user->M); // M is Minv 315 CHKERRQ(ierr); 316 317 ierr = DMRestoreLocalVector(user->dm, &Qloc); CHKERRQ(ierr); 318 ierr = DMRestoreLocalVector(user->dm, &Gloc); CHKERRQ(ierr); 319 PetscFunctionReturn(0); 320 } 321 322 static PetscErrorCode IFunction_NS(TS ts, PetscReal t, Vec Q, Vec Qdot, Vec G, 323 void *userData) { 324 PetscErrorCode ierr; 325 User user = *(User *)userData; 326 const PetscScalar *q, *qdot; 327 PetscScalar *g; 328 Vec Qloc, Qdotloc, Gloc; 329 330 // Global-to-local 331 PetscFunctionBeginUser; 332 ierr = DMGetLocalVector(user->dm, &Qloc); CHKERRQ(ierr); 333 ierr = DMGetLocalVector(user->dm, &Qdotloc); CHKERRQ(ierr); 334 ierr = DMGetLocalVector(user->dm, &Gloc); CHKERRQ(ierr); 335 ierr = VecZeroEntries(Qloc); CHKERRQ(ierr); 336 ierr = DMGlobalToLocal(user->dm, Q, INSERT_VALUES, Qloc); CHKERRQ(ierr); 337 ierr = DMPlexInsertBoundaryValues(user->dm, PETSC_TRUE, Qloc, 0.0, 338 NULL, NULL, NULL); CHKERRQ(ierr); 339 ierr = VecZeroEntries(Qdotloc); CHKERRQ(ierr); 340 ierr = DMGlobalToLocal(user->dm, Qdot, INSERT_VALUES, Qdotloc); CHKERRQ(ierr); 341 ierr = VecZeroEntries(Gloc); CHKERRQ(ierr); 342 343 // Ceed Vectors 344 ierr = VecGetArrayRead(Qloc, &q); CHKERRQ(ierr); 345 ierr = VecGetArrayRead(Qdotloc, &qdot); CHKERRQ(ierr); 346 ierr = VecGetArray(Gloc, &g); CHKERRQ(ierr); 347 CeedVectorSetArray(user->qceed, CEED_MEM_HOST, CEED_USE_POINTER, 348 (PetscScalar *)q); 349 CeedVectorSetArray(user->qdotceed, CEED_MEM_HOST, CEED_USE_POINTER, 350 (PetscScalar *)qdot); 351 CeedVectorSetArray(user->gceed, CEED_MEM_HOST, CEED_USE_POINTER, g); 352 353 // Apply CEED operator 354 CeedOperatorApply(user->op_ifunction, user->qceed, user->gceed, 355 CEED_REQUEST_IMMEDIATE); 356 357 // Restore vectors 358 ierr = VecRestoreArrayRead(Qloc, &q); CHKERRQ(ierr); 359 ierr = VecRestoreArrayRead(Qdotloc, &qdot); CHKERRQ(ierr); 360 ierr = VecRestoreArray(Gloc, &g); CHKERRQ(ierr); 361 362 ierr = VecZeroEntries(G); CHKERRQ(ierr); 363 ierr = DMLocalToGlobal(user->dm, Gloc, ADD_VALUES, G); CHKERRQ(ierr); 364 365 ierr = DMRestoreLocalVector(user->dm, &Qloc); CHKERRQ(ierr); 366 ierr = DMRestoreLocalVector(user->dm, &Qdotloc); CHKERRQ(ierr); 367 ierr = DMRestoreLocalVector(user->dm, &Gloc); CHKERRQ(ierr); 368 PetscFunctionReturn(0); 369 } 370 371 // User provided TS Monitor 372 static PetscErrorCode TSMonitor_NS(TS ts, PetscInt stepno, PetscReal time, 373 Vec Q, void *ctx) { 374 User user = ctx; 375 Vec Qloc; 376 char filepath[PETSC_MAX_PATH_LEN]; 377 PetscViewer viewer; 378 PetscErrorCode ierr; 379 380 // Set up output 381 PetscFunctionBeginUser; 382 // Print every 'outputfreq' steps 383 if (stepno % user->outputfreq != 0) 384 PetscFunctionReturn(0); 385 ierr = DMGetLocalVector(user->dm, &Qloc); CHKERRQ(ierr); 386 ierr = PetscObjectSetName((PetscObject)Qloc, "StateVec"); CHKERRQ(ierr); 387 ierr = VecZeroEntries(Qloc); CHKERRQ(ierr); 388 ierr = DMGlobalToLocal(user->dm, Q, INSERT_VALUES, Qloc); CHKERRQ(ierr); 389 390 // Output 391 ierr = PetscSNPrintf(filepath, sizeof filepath, "%s/ns-%03D.vtu", 392 user->outputfolder, stepno + user->contsteps); 393 CHKERRQ(ierr); 394 ierr = PetscViewerVTKOpen(PetscObjectComm((PetscObject)Q), filepath, 395 FILE_MODE_WRITE, &viewer); CHKERRQ(ierr); 396 ierr = VecView(Qloc, viewer); CHKERRQ(ierr); 397 if (user->dmviz) { 398 Vec Qrefined, Qrefined_loc; 399 char filepath_refined[PETSC_MAX_PATH_LEN]; 400 PetscViewer viewer_refined; 401 402 ierr = DMGetGlobalVector(user->dmviz, &Qrefined); CHKERRQ(ierr); 403 ierr = DMGetLocalVector(user->dmviz, &Qrefined_loc); CHKERRQ(ierr); 404 ierr = PetscObjectSetName((PetscObject)Qrefined_loc, "Refined"); 405 CHKERRQ(ierr); 406 ierr = MatInterpolate(user->interpviz, Q, Qrefined); CHKERRQ(ierr); 407 ierr = VecZeroEntries(Qrefined_loc); CHKERRQ(ierr); 408 ierr = DMGlobalToLocal(user->dmviz, Qrefined, INSERT_VALUES, Qrefined_loc); 409 CHKERRQ(ierr); 410 ierr = PetscSNPrintf(filepath_refined, sizeof filepath_refined, 411 "%s/nsrefined-%03D.vtu", 412 user->outputfolder, stepno + user->contsteps); 413 CHKERRQ(ierr); 414 ierr = PetscViewerVTKOpen(PetscObjectComm((PetscObject)Qrefined), 415 filepath_refined, 416 FILE_MODE_WRITE, &viewer_refined); CHKERRQ(ierr); 417 ierr = VecView(Qrefined_loc, viewer_refined); CHKERRQ(ierr); 418 ierr = DMRestoreLocalVector(user->dmviz, &Qrefined_loc); CHKERRQ(ierr); 419 ierr = DMRestoreGlobalVector(user->dmviz, &Qrefined); CHKERRQ(ierr); 420 ierr = PetscViewerDestroy(&viewer_refined); CHKERRQ(ierr); 421 } 422 ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); 423 ierr = DMRestoreLocalVector(user->dm, &Qloc); CHKERRQ(ierr); 424 425 // Save data in a binary file for continuation of simulations 426 ierr = PetscSNPrintf(filepath, sizeof filepath, "%s/ns-solution.bin", 427 user->outputfolder); CHKERRQ(ierr); 428 ierr = PetscViewerBinaryOpen(user->comm, filepath, FILE_MODE_WRITE, &viewer); 429 CHKERRQ(ierr); 430 ierr = VecView(Q, viewer); CHKERRQ(ierr); 431 ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); 432 433 // Save time stamp 434 // Dimensionalize time back 435 time /= user->units->second; 436 ierr = PetscSNPrintf(filepath, sizeof filepath, "%s/ns-time.bin", 437 user->outputfolder); CHKERRQ(ierr); 438 ierr = PetscViewerBinaryOpen(user->comm, filepath, FILE_MODE_WRITE, &viewer); 439 CHKERRQ(ierr); 440 #if PETSC_VERSION_GE(3,13,0) 441 ierr = PetscViewerBinaryWrite(viewer, &time, 1, PETSC_REAL); 442 #else 443 ierr = PetscViewerBinaryWrite(viewer, &time, 1, PETSC_REAL, true); 444 #endif 445 CHKERRQ(ierr); 446 ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); 447 448 PetscFunctionReturn(0); 449 } 450 451 static PetscErrorCode ICs_PetscMultiplicity(CeedOperator op_ics, 452 CeedVector xcorners, CeedVector q0ceed, DM dm, Vec Qloc, Vec Q, 453 CeedElemRestriction restrictq, SetupContext ctxSetup, CeedScalar time) { 454 PetscErrorCode ierr; 455 CeedVector multlvec; 456 Vec Multiplicity, MultiplicityLoc; 457 458 ctxSetup->time = time; 459 ierr = VecZeroEntries(Qloc); CHKERRQ(ierr); 460 ierr = VectorPlacePetscVec(q0ceed, Qloc); CHKERRQ(ierr); 461 CeedOperatorApply(op_ics, xcorners, q0ceed, CEED_REQUEST_IMMEDIATE); 462 ierr = VecZeroEntries(Q); CHKERRQ(ierr); 463 ierr = DMLocalToGlobal(dm, Qloc, ADD_VALUES, Q); CHKERRQ(ierr); 464 465 // Fix multiplicity for output of ICs 466 ierr = DMGetLocalVector(dm, &MultiplicityLoc); CHKERRQ(ierr); 467 CeedElemRestrictionCreateVector(restrictq, &multlvec, NULL); 468 ierr = VectorPlacePetscVec(multlvec, MultiplicityLoc); CHKERRQ(ierr); 469 CeedElemRestrictionGetMultiplicity(restrictq, multlvec); 470 CeedVectorDestroy(&multlvec); 471 ierr = DMGetGlobalVector(dm, &Multiplicity); CHKERRQ(ierr); 472 ierr = VecZeroEntries(Multiplicity); CHKERRQ(ierr); 473 ierr = DMLocalToGlobal(dm, MultiplicityLoc, ADD_VALUES, Multiplicity); 474 CHKERRQ(ierr); 475 ierr = VecPointwiseDivide(Q, Q, Multiplicity); CHKERRQ(ierr); 476 ierr = VecPointwiseDivide(Qloc, Qloc, MultiplicityLoc); CHKERRQ(ierr); 477 ierr = DMRestoreLocalVector(dm, &MultiplicityLoc); CHKERRQ(ierr); 478 ierr = DMRestoreGlobalVector(dm, &Multiplicity); CHKERRQ(ierr); 479 480 PetscFunctionReturn(0); 481 } 482 483 static PetscErrorCode ComputeLumpedMassMatrix(Ceed ceed, DM dm, 484 CeedElemRestriction restrictq, CeedBasis basisq, 485 CeedElemRestriction restrictqdi, CeedVector qdata, Vec M) { 486 PetscErrorCode ierr; 487 CeedQFunction qf_mass; 488 CeedOperator op_mass; 489 CeedVector mceed; 490 Vec Mloc; 491 CeedInt ncompq, qdatasize; 492 493 PetscFunctionBeginUser; 494 CeedElemRestrictionGetNumComponents(restrictq, &ncompq); 495 CeedElemRestrictionGetNumComponents(restrictqdi, &qdatasize); 496 // Create the Q-function that defines the action of the mass operator 497 CeedQFunctionCreateInterior(ceed, 1, Mass, Mass_loc, &qf_mass); 498 CeedQFunctionAddInput(qf_mass, "q", ncompq, CEED_EVAL_INTERP); 499 CeedQFunctionAddInput(qf_mass, "qdata", qdatasize, CEED_EVAL_NONE); 500 CeedQFunctionAddOutput(qf_mass, "v", ncompq, CEED_EVAL_INTERP); 501 502 // Create the mass operator 503 CeedOperatorCreate(ceed, qf_mass, NULL, NULL, &op_mass); 504 CeedOperatorSetField(op_mass, "q", restrictq, basisq, CEED_VECTOR_ACTIVE); 505 CeedOperatorSetField(op_mass, "qdata", restrictqdi, 506 CEED_BASIS_COLLOCATED, qdata); 507 CeedOperatorSetField(op_mass, "v", restrictq, basisq, CEED_VECTOR_ACTIVE); 508 509 ierr = DMGetLocalVector(dm, &Mloc); CHKERRQ(ierr); 510 ierr = VecZeroEntries(Mloc); CHKERRQ(ierr); 511 CeedElemRestrictionCreateVector(restrictq, &mceed, NULL); 512 ierr = VectorPlacePetscVec(mceed, Mloc); CHKERRQ(ierr); 513 514 { 515 // Compute a lumped mass matrix 516 CeedVector onesvec; 517 CeedElemRestrictionCreateVector(restrictq, &onesvec, NULL); 518 CeedVectorSetValue(onesvec, 1.0); 519 CeedOperatorApply(op_mass, onesvec, mceed, CEED_REQUEST_IMMEDIATE); 520 CeedVectorDestroy(&onesvec); 521 CeedOperatorDestroy(&op_mass); 522 CeedVectorDestroy(&mceed); 523 } 524 CeedQFunctionDestroy(&qf_mass); 525 526 ierr = VecZeroEntries(M); CHKERRQ(ierr); 527 ierr = DMLocalToGlobal(dm, Mloc, ADD_VALUES, M); CHKERRQ(ierr); 528 ierr = DMRestoreLocalVector(dm, &Mloc); CHKERRQ(ierr); 529 530 // Invert diagonally lumped mass vector for RHS function 531 ierr = VecReciprocal(M); CHKERRQ(ierr); 532 PetscFunctionReturn(0); 533 } 534 535 PetscErrorCode SetUpDM(DM dm, problemData *problem, PetscInt degree, 536 SimpleBC bc, void *ctxSetup) { 537 PetscErrorCode ierr; 538 539 PetscFunctionBeginUser; 540 { 541 // Configure the finite element space and boundary conditions 542 PetscFE fe; 543 PetscSpace fespace; 544 PetscInt ncompq = 5; 545 ierr = PetscFECreateLagrange(PETSC_COMM_SELF, problem->dim, ncompq, 546 PETSC_FALSE, degree, PETSC_DECIDE, 547 &fe); 548 ierr = PetscObjectSetName((PetscObject)fe, "Q"); CHKERRQ(ierr); 549 ierr = DMAddField(dm,NULL,(PetscObject)fe); CHKERRQ(ierr); 550 ierr = DMCreateDS(dm); CHKERRQ(ierr); 551 /* Wall boundary conditions are zero velocity and zero flux for density and energy */ 552 { 553 PetscInt comps[3] = {1, 2, 3}; 554 ierr = DMAddBoundary(dm, DM_BC_ESSENTIAL, "wall", "Face Sets", 0, 555 3, comps, (void(*)(void))problem->bc, 556 bc->nwall, bc->walls, ctxSetup); CHKERRQ(ierr); 557 } 558 { 559 PetscInt comps[1] = {1}; 560 ierr = DMAddBoundary(dm, DM_BC_ESSENTIAL, "slipx", "Face Sets", 0, 561 1, comps, (void(*)(void))NULL, bc->nslip[0], 562 bc->slips[0], ctxSetup); CHKERRQ(ierr); 563 comps[0] = 2; 564 ierr = DMAddBoundary(dm, DM_BC_ESSENTIAL, "slipy", "Face Sets", 0, 565 1, comps, (void(*)(void))NULL, bc->nslip[1], 566 bc->slips[1], ctxSetup); CHKERRQ(ierr); 567 comps[0] = 3; 568 ierr = DMAddBoundary(dm, DM_BC_ESSENTIAL, "slipz", "Face Sets", 0, 569 1, comps, (void(*)(void))NULL, bc->nslip[2], 570 bc->slips[2], ctxSetup); CHKERRQ(ierr); 571 } 572 ierr = DMPlexSetClosurePermutationTensor(dm,PETSC_DETERMINE,NULL); 573 CHKERRQ(ierr); 574 ierr = PetscFEGetBasisSpace(fe, &fespace); CHKERRQ(ierr); 575 ierr = PetscFEDestroy(&fe); CHKERRQ(ierr); 576 } 577 { 578 // Empty name for conserved field (because there is only one field) 579 PetscSection section; 580 ierr = DMGetLocalSection(dm, §ion); CHKERRQ(ierr); 581 ierr = PetscSectionSetFieldName(section, 0, ""); CHKERRQ(ierr); 582 ierr = PetscSectionSetComponentName(section, 0, 0, "Density"); 583 CHKERRQ(ierr); 584 ierr = PetscSectionSetComponentName(section, 0, 1, "MomentumX"); 585 CHKERRQ(ierr); 586 ierr = PetscSectionSetComponentName(section, 0, 2, "MomentumY"); 587 CHKERRQ(ierr); 588 ierr = PetscSectionSetComponentName(section, 0, 3, "MomentumZ"); 589 CHKERRQ(ierr); 590 ierr = PetscSectionSetComponentName(section, 0, 4, "EnergyDensity"); 591 CHKERRQ(ierr); 592 } 593 PetscFunctionReturn(0); 594 } 595 596 int main(int argc, char **argv) { 597 PetscInt ierr; 598 MPI_Comm comm; 599 DM dm, dmcoord, dmviz, dmvizfine; 600 Mat interpviz; 601 TS ts; 602 TSAdapt adapt; 603 User user; 604 Units units; 605 char ceedresource[4096] = "/cpu/self"; 606 PetscInt cStart, cEnd, localNelem, lnodes, steps; 607 const PetscInt ncompq = 5; 608 PetscMPIInt rank; 609 PetscScalar ftime; 610 Vec Q, Qloc, Xloc; 611 Ceed ceed; 612 CeedInt numP, numQ; 613 CeedVector xcorners, qdata, q0ceed; 614 CeedBasis basisx, basisxc, basisq; 615 CeedElemRestriction restrictx, restrictq, restrictqdi; 616 CeedQFunction qf_setup, qf_ics, qf_rhs, qf_ifunction; 617 CeedOperator op_setup, op_ics; 618 CeedScalar Rd; 619 PetscScalar WpermK, Pascal, JperkgK, mpersquareds, kgpercubicm, 620 kgpersquaredms, Joulepercubicm; 621 problemType problemChoice; 622 problemData *problem = NULL; 623 StabilizationType stab; 624 PetscBool test, implicit; 625 PetscInt viz_refine = 0; 626 struct SimpleBC_ bc = { 627 .nwall = 6, 628 .walls = {1,2,3,4,5,6}, 629 }; 630 double start, cpu_time_used; 631 632 // Create the libCEED contexts 633 PetscScalar meter = 1e-2; // 1 meter in scaled length units 634 PetscScalar second = 1e-2; // 1 second in scaled time units 635 PetscScalar kilogram = 1e-6; // 1 kilogram in scaled mass units 636 PetscScalar Kelvin = 1; // 1 Kelvin in scaled temperature units 637 CeedScalar theta0 = 300.; // K 638 CeedScalar thetaC = -15.; // K 639 CeedScalar P0 = 1.e5; // Pa 640 CeedScalar N = 0.01; // 1/s 641 CeedScalar cv = 717.; // J/(kg K) 642 CeedScalar cp = 1004.; // J/(kg K) 643 CeedScalar g = 9.81; // m/s^2 644 CeedScalar lambda = -2./3.; // - 645 CeedScalar mu = 75.; // Pa s, dynamic viscosity 646 // mu = 75 is not physical for air, but is good for numerical stability 647 CeedScalar k = 0.02638; // W/(m K) 648 CeedScalar CtauS = 0.; // dimensionless 649 CeedScalar strong_form = 0.; // [0,1] 650 PetscScalar lx = 8000.; // m 651 PetscScalar ly = 8000.; // m 652 PetscScalar lz = 4000.; // m 653 CeedScalar rc = 1000.; // m (Radius of bubble) 654 PetscScalar resx = 1000.; // m (resolution in x) 655 PetscScalar resy = 1000.; // m (resolution in y) 656 PetscScalar resz = 1000.; // m (resolution in z) 657 PetscInt outputfreq = 10; // - 658 PetscInt contsteps = 0; // - 659 PetscInt degree = 1; // - 660 PetscInt qextra = 2; // - 661 DMBoundaryType periodicity[] = {DM_BOUNDARY_NONE, DM_BOUNDARY_NONE, 662 DM_BOUNDARY_NONE 663 }; 664 PetscReal center[3], dc_axis[3] = {0, 0, 0}; 665 666 ierr = PetscInitialize(&argc, &argv, NULL, help); 667 if (ierr) return ierr; 668 669 // Allocate PETSc context 670 ierr = PetscCalloc1(1, &user); CHKERRQ(ierr); 671 ierr = PetscMalloc1(1, &units); CHKERRQ(ierr); 672 673 // Parse command line options 674 comm = PETSC_COMM_WORLD; 675 ierr = PetscOptionsBegin(comm, NULL, "Navier-Stokes in PETSc with libCEED", 676 NULL); CHKERRQ(ierr); 677 ierr = PetscOptionsString("-ceed", "CEED resource specifier", 678 NULL, ceedresource, ceedresource, 679 sizeof(ceedresource), NULL); CHKERRQ(ierr); 680 ierr = PetscOptionsBool("-test", "Run in test mode", 681 NULL, test=PETSC_FALSE, &test, NULL); CHKERRQ(ierr); 682 problemChoice = NS_DENSITY_CURRENT; 683 ierr = PetscOptionsEnum("-problem", "Problem to solve", NULL, 684 problemTypes, (PetscEnum)problemChoice, 685 (PetscEnum *)&problemChoice, NULL); CHKERRQ(ierr); 686 problem = &problemOptions[problemChoice]; 687 ierr = PetscOptionsEnum("-stab", "Stabilization method", NULL, 688 StabilizationTypes, (PetscEnum)(stab = STAB_NONE), 689 (PetscEnum *)&stab, NULL); CHKERRQ(ierr); 690 ierr = PetscOptionsBool("-implicit", "Use implicit (IFunction) formulation", 691 NULL, implicit=PETSC_FALSE, &implicit, NULL); 692 CHKERRQ(ierr); 693 { 694 PetscInt len; 695 PetscBool flg; 696 ierr = PetscOptionsIntArray("-bc_wall", 697 "Use wall boundary conditions on this list of faces", 698 NULL, bc.walls, 699 (len = sizeof(bc.walls) / sizeof(bc.walls[0]), 700 &len), &flg); CHKERRQ(ierr); 701 if (flg) bc.nwall = len; 702 for (PetscInt j=0; j<3; j++) { 703 const char *flags[3] = {"-bc_slip_x", "-bc_slip_y", "-bc_slip_z"}; 704 ierr = PetscOptionsIntArray(flags[j], 705 "Use slip boundary conditions on this list of faces", 706 NULL, bc.slips[j], 707 (len = sizeof(bc.slips[j]) / sizeof(bc.slips[j][0]), 708 &len), &flg); 709 CHKERRQ(ierr); 710 if (flg) bc.nslip[j] = len; 711 } 712 } 713 ierr = PetscOptionsInt("-viz_refine", 714 "Regular refinement levels for visualization", 715 NULL, viz_refine, &viz_refine, NULL); 716 CHKERRQ(ierr); 717 ierr = PetscOptionsScalar("-units_meter", "1 meter in scaled length units", 718 NULL, meter, &meter, NULL); CHKERRQ(ierr); 719 meter = fabs(meter); 720 ierr = PetscOptionsScalar("-units_second","1 second in scaled time units", 721 NULL, second, &second, NULL); CHKERRQ(ierr); 722 second = fabs(second); 723 ierr = PetscOptionsScalar("-units_kilogram","1 kilogram in scaled mass units", 724 NULL, kilogram, &kilogram, NULL); CHKERRQ(ierr); 725 kilogram = fabs(kilogram); 726 ierr = PetscOptionsScalar("-units_Kelvin", 727 "1 Kelvin in scaled temperature units", 728 NULL, Kelvin, &Kelvin, NULL); CHKERRQ(ierr); 729 Kelvin = fabs(Kelvin); 730 ierr = PetscOptionsScalar("-theta0", "Reference potential temperature", 731 NULL, theta0, &theta0, NULL); CHKERRQ(ierr); 732 ierr = PetscOptionsScalar("-thetaC", "Perturbation of potential temperature", 733 NULL, thetaC, &thetaC, NULL); CHKERRQ(ierr); 734 ierr = PetscOptionsScalar("-P0", "Atmospheric pressure", 735 NULL, P0, &P0, NULL); CHKERRQ(ierr); 736 ierr = PetscOptionsScalar("-N", "Brunt-Vaisala frequency", 737 NULL, N, &N, NULL); CHKERRQ(ierr); 738 ierr = PetscOptionsScalar("-cv", "Heat capacity at constant volume", 739 NULL, cv, &cv, NULL); CHKERRQ(ierr); 740 ierr = PetscOptionsScalar("-cp", "Heat capacity at constant pressure", 741 NULL, cp, &cp, NULL); CHKERRQ(ierr); 742 ierr = PetscOptionsScalar("-g", "Gravitational acceleration", 743 NULL, g, &g, NULL); CHKERRQ(ierr); 744 ierr = PetscOptionsScalar("-lambda", 745 "Stokes hypothesis second viscosity coefficient", 746 NULL, lambda, &lambda, NULL); CHKERRQ(ierr); 747 ierr = PetscOptionsScalar("-mu", "Shear dynamic viscosity coefficient", 748 NULL, mu, &mu, NULL); CHKERRQ(ierr); 749 ierr = PetscOptionsScalar("-k", "Thermal conductivity", 750 NULL, k, &k, NULL); CHKERRQ(ierr); 751 ierr = PetscOptionsScalar("-CtauS", 752 "Scale coefficient for tau (nondimensional)", 753 NULL, CtauS, &CtauS, NULL); CHKERRQ(ierr); 754 ierr = PetscOptionsScalar("-strong_form", 755 "Strong (1) or weak/integrated by parts (0) advection residual", 756 NULL, strong_form, &strong_form, NULL); 757 CHKERRQ(ierr); 758 ierr = PetscOptionsScalar("-lx", "Length scale in x direction", 759 NULL, lx, &lx, NULL); CHKERRQ(ierr); 760 ierr = PetscOptionsScalar("-ly", "Length scale in y direction", 761 NULL, ly, &ly, NULL); CHKERRQ(ierr); 762 ierr = PetscOptionsScalar("-lz", "Length scale in z direction", 763 NULL, lz, &lz, NULL); CHKERRQ(ierr); 764 ierr = PetscOptionsScalar("-rc", "Characteristic radius of thermal bubble", 765 NULL, rc, &rc, NULL); CHKERRQ(ierr); 766 ierr = PetscOptionsScalar("-resx","Target resolution in x", 767 NULL, resx, &resx, NULL); CHKERRQ(ierr); 768 ierr = PetscOptionsScalar("-resy","Target resolution in y", 769 NULL, resy, &resy, NULL); CHKERRQ(ierr); 770 ierr = PetscOptionsScalar("-resz","Target resolution in z", 771 NULL, resz, &resz, NULL); CHKERRQ(ierr); 772 PetscInt n = problem->dim; 773 ierr = PetscOptionsEnumArray("-periodicity", "Periodicity per direction", 774 NULL, DMBoundaryTypes, (PetscEnum *)periodicity, 775 &n, NULL); CHKERRQ(ierr); 776 n = problem->dim; 777 center[0] = 0.5 * lx; 778 center[1] = 0.5 * ly; 779 center[2] = 0.5 * lz; 780 ierr = PetscOptionsRealArray("-center", "Location of bubble center", 781 NULL, center, &n, NULL); CHKERRQ(ierr); 782 n = problem->dim; 783 ierr = PetscOptionsRealArray("-dc_axis", 784 "Axis of density current cylindrical anomaly, or {0,0,0} for spherically symmetric", 785 NULL, dc_axis, &n, NULL); CHKERRQ(ierr); 786 { 787 PetscReal norm = PetscSqrtReal(PetscSqr(dc_axis[0]) + 788 PetscSqr(dc_axis[1]) + PetscSqr(dc_axis[2])); 789 if (norm > 0) { 790 for (int i=0; i<3; i++) dc_axis[i] /= norm; 791 } 792 } 793 ierr = PetscOptionsInt("-output_freq", 794 "Frequency of output, in number of steps", 795 NULL, outputfreq, &outputfreq, NULL); CHKERRQ(ierr); 796 ierr = PetscOptionsInt("-continue", "Continue from previous solution", 797 NULL, contsteps, &contsteps, NULL); CHKERRQ(ierr); 798 ierr = PetscOptionsInt("-degree", "Polynomial degree of finite elements", 799 NULL, degree, °ree, NULL); CHKERRQ(ierr); 800 ierr = PetscOptionsInt("-qextra", "Number of extra quadrature points", 801 NULL, qextra, &qextra, NULL); CHKERRQ(ierr); 802 PetscStrncpy(user->outputfolder, ".", 2); 803 ierr = PetscOptionsString("-of", "Output folder", 804 NULL, user->outputfolder, user->outputfolder, 805 sizeof(user->outputfolder), NULL); CHKERRQ(ierr); 806 ierr = PetscOptionsEnd(); CHKERRQ(ierr); 807 808 // Define derived units 809 Pascal = kilogram / (meter * PetscSqr(second)); 810 JperkgK = PetscSqr(meter) / (PetscSqr(second) * Kelvin); 811 mpersquareds = meter / PetscSqr(second); 812 WpermK = kilogram * meter / (pow(second,3) * Kelvin); 813 kgpercubicm = kilogram / pow(meter,3); 814 kgpersquaredms = kilogram / (PetscSqr(meter) * second); 815 Joulepercubicm = kilogram / (meter * PetscSqr(second)); 816 817 // Scale variables to desired units 818 theta0 *= Kelvin; 819 thetaC *= Kelvin; 820 P0 *= Pascal; 821 N *= (1./second); 822 cv *= JperkgK; 823 cp *= JperkgK; 824 Rd = cp - cv; 825 g *= mpersquareds; 826 mu *= Pascal * second; 827 k *= WpermK; 828 lx = fabs(lx) * meter; 829 ly = fabs(ly) * meter; 830 lz = fabs(lz) * meter; 831 rc = fabs(rc) * meter; 832 resx = fabs(resx) * meter; 833 resy = fabs(resy) * meter; 834 resz = fabs(resz) * meter; 835 for (int i=0; i<3; i++) center[i] *= meter; 836 837 const CeedInt dim = problem->dim, ncompx = problem->dim, 838 qdatasize = problem->qdatasize; 839 // Set up the libCEED context 840 struct SetupContext_ ctxSetup = { 841 .theta0 = theta0, 842 .thetaC = thetaC, 843 .P0 = P0, 844 .N = N, 845 .cv = cv, 846 .cp = cp, 847 .Rd = Rd, 848 .g = g, 849 .rc = rc, 850 .lx = lx, 851 .ly = ly, 852 .lz = lz, 853 .periodicity0 = periodicity[0], 854 .periodicity1 = periodicity[1], 855 .periodicity2 = periodicity[2], 856 .center[0] = center[0], 857 .center[1] = center[1], 858 .center[2] = center[2], 859 .dc_axis[0] = dc_axis[0], 860 .dc_axis[1] = dc_axis[1], 861 .dc_axis[2] = dc_axis[2], 862 .time = 0, 863 }; 864 865 { 866 const PetscReal scale[3] = {lx, ly, lz}; 867 ierr = DMPlexCreateBoxMesh(comm, dim, PETSC_FALSE, NULL, NULL, scale, 868 periodicity, PETSC_TRUE, &dm); 869 CHKERRQ(ierr); 870 } 871 if (1) { 872 DM dmDist = NULL; 873 PetscPartitioner part; 874 875 ierr = DMPlexGetPartitioner(dm, &part); CHKERRQ(ierr); 876 ierr = PetscPartitionerSetFromOptions(part); CHKERRQ(ierr); 877 ierr = DMPlexDistribute(dm, 0, NULL, &dmDist); CHKERRQ(ierr); 878 if (dmDist) { 879 ierr = DMDestroy(&dm); CHKERRQ(ierr); 880 dm = dmDist; 881 } 882 } 883 ierr = DMViewFromOptions(dm, NULL, "-dm_view"); CHKERRQ(ierr); 884 885 ierr = DMLocalizeCoordinates(dm); CHKERRQ(ierr); 886 ierr = DMSetFromOptions(dm); CHKERRQ(ierr); 887 ierr = SetUpDM(dm, problem, degree, &bc, &ctxSetup); CHKERRQ(ierr); 888 if (!test) { 889 ierr = PetscPrintf(PETSC_COMM_WORLD, 890 "Degree of FEM Space: %D\n", 891 degree); CHKERRQ(ierr); 892 } 893 dmviz = NULL; 894 interpviz = NULL; 895 if (viz_refine) { 896 DM dmhierarchy[viz_refine+1]; 897 898 ierr = DMPlexSetRefinementUniform(dm, PETSC_TRUE); CHKERRQ(ierr); 899 dmhierarchy[0] = dm; 900 for (PetscInt i = 0, d = degree; i < viz_refine; i++) { 901 Mat interp_next; 902 903 ierr = DMRefine(dmhierarchy[i], MPI_COMM_NULL, &dmhierarchy[i+1]); 904 CHKERRQ(ierr); 905 ierr = DMSetCoarseDM(dmhierarchy[i+1], dmhierarchy[i]); CHKERRQ(ierr); 906 d = (d + 1) / 2; 907 if (i + 1 == viz_refine) d = 1; 908 ierr = SetUpDM(dmhierarchy[i+1], problem, d, &bc, &ctxSetup); CHKERRQ(ierr); 909 ierr = DMCreateInterpolation(dmhierarchy[i], dmhierarchy[i+1], 910 &interp_next, NULL); CHKERRQ(ierr); 911 if (!i) interpviz = interp_next; 912 else { 913 Mat C; 914 ierr = MatMatMult(interp_next, interpviz, MAT_INITIAL_MATRIX, 915 PETSC_DECIDE, &C); CHKERRQ(ierr); 916 ierr = MatDestroy(&interp_next); CHKERRQ(ierr); 917 ierr = MatDestroy(&interpviz); CHKERRQ(ierr); 918 interpviz = C; 919 } 920 } 921 for (PetscInt i=1; i<viz_refine; i++) { 922 ierr = DMDestroy(&dmhierarchy[i]); CHKERRQ(ierr); 923 } 924 dmviz = dmhierarchy[viz_refine]; 925 } 926 ierr = DMCreateGlobalVector(dm, &Q); CHKERRQ(ierr); 927 ierr = DMGetLocalVector(dm, &Qloc); CHKERRQ(ierr); 928 ierr = VecGetSize(Qloc, &lnodes); CHKERRQ(ierr); 929 lnodes /= ncompq; 930 931 { 932 // Print grid information 933 CeedInt gdofs, odofs; 934 int comm_size; 935 char box_faces_str[PETSC_MAX_PATH_LEN] = "NONE"; 936 ierr = VecGetSize(Q, &gdofs); CHKERRQ(ierr); 937 ierr = VecGetLocalSize(Q, &odofs); CHKERRQ(ierr); 938 ierr = MPI_Comm_size(comm, &comm_size); CHKERRQ(ierr); 939 ierr = PetscOptionsGetString(NULL, NULL, "-dm_plex_box_faces", box_faces_str, 940 sizeof(box_faces_str), NULL); CHKERRQ(ierr); 941 if (!test) { 942 ierr = PetscPrintf(comm, "Global FEM dofs: %D (%D owned) on %d ranks\n", 943 gdofs, odofs, comm_size); CHKERRQ(ierr); 944 ierr = PetscPrintf(comm, "Local FEM nodes: %D\n", lnodes); CHKERRQ(ierr); 945 ierr = PetscPrintf(comm, "dm_plex_box_faces: %s\n", box_faces_str); 946 CHKERRQ(ierr); 947 } 948 949 } 950 951 // Set up global mass vector 952 ierr = VecDuplicate(Q,&user->M); CHKERRQ(ierr); 953 954 // Set up CEED 955 // CEED Bases 956 CeedInit(ceedresource, &ceed); 957 numP = degree + 1; 958 numQ = numP + qextra; 959 CeedBasisCreateTensorH1Lagrange(ceed, dim, ncompq, numP, numQ, CEED_GAUSS, 960 &basisq); 961 CeedBasisCreateTensorH1Lagrange(ceed, dim, ncompx, 2, numQ, CEED_GAUSS, 962 &basisx); 963 CeedBasisCreateTensorH1Lagrange(ceed, dim, ncompx, 2, numP, 964 CEED_GAUSS_LOBATTO, &basisxc); 965 966 ierr = DMGetCoordinateDM(dm, &dmcoord); CHKERRQ(ierr); 967 ierr = DMPlexSetClosurePermutationTensor(dmcoord, PETSC_DETERMINE, NULL); 968 CHKERRQ(ierr); 969 970 // CEED Restrictions 971 ierr = CreateRestrictionFromPlex(ceed, dm, degree+1, &restrictq); 972 CHKERRQ(ierr); 973 ierr = CreateRestrictionFromPlex(ceed, dmcoord, 2, &restrictx); CHKERRQ(ierr); 974 DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd); CHKERRQ(ierr); 975 localNelem = cEnd - cStart; 976 CeedInt numQdim = CeedIntPow(numQ, dim); 977 CeedElemRestrictionCreateStrided(ceed, localNelem, numQdim, 978 qdatasize, qdatasize*localNelem*numQdim, 979 CEED_STRIDES_BACKEND, &restrictqdi); 980 981 ierr = DMGetCoordinatesLocal(dm, &Xloc); CHKERRQ(ierr); 982 ierr = CreateVectorFromPetscVec(ceed, Xloc, &xcorners); CHKERRQ(ierr); 983 984 // Create the CEED vectors that will be needed in setup 985 CeedInt Nqpts; 986 CeedBasisGetNumQuadraturePoints(basisq, &Nqpts); 987 CeedInt Ndofs = 1; 988 for (int d=0; d<3; d++) Ndofs *= numP; 989 CeedVectorCreate(ceed, qdatasize*localNelem*Nqpts, &qdata); 990 CeedElemRestrictionCreateVector(restrictq, &q0ceed, NULL); 991 992 // Create the Q-function that builds the quadrature data for the NS operator 993 CeedQFunctionCreateInterior(ceed, 1, problem->setup, problem->setup_loc, 994 &qf_setup); 995 CeedQFunctionAddInput(qf_setup, "dx", ncompx*dim, CEED_EVAL_GRAD); 996 CeedQFunctionAddInput(qf_setup, "weight", 1, CEED_EVAL_WEIGHT); 997 CeedQFunctionAddOutput(qf_setup, "qdata", qdatasize, CEED_EVAL_NONE); 998 999 // Create the Q-function that sets the ICs of the operator 1000 CeedQFunctionCreateInterior(ceed, 1, problem->ics, problem->ics_loc, &qf_ics); 1001 CeedQFunctionAddInput(qf_ics, "x", ncompx, CEED_EVAL_INTERP); 1002 CeedQFunctionAddOutput(qf_ics, "q0", ncompq, CEED_EVAL_NONE); 1003 1004 qf_rhs = NULL; 1005 if (problem->apply_rhs) { // Create the Q-function that defines the action of the RHS operator 1006 CeedQFunctionCreateInterior(ceed, 1, problem->apply_rhs, 1007 problem->apply_rhs_loc, &qf_rhs); 1008 CeedQFunctionAddInput(qf_rhs, "q", ncompq, CEED_EVAL_INTERP); 1009 CeedQFunctionAddInput(qf_rhs, "dq", ncompq*dim, CEED_EVAL_GRAD); 1010 CeedQFunctionAddInput(qf_rhs, "qdata", qdatasize, CEED_EVAL_NONE); 1011 CeedQFunctionAddInput(qf_rhs, "x", ncompx, CEED_EVAL_INTERP); 1012 CeedQFunctionAddOutput(qf_rhs, "v", ncompq, CEED_EVAL_INTERP); 1013 CeedQFunctionAddOutput(qf_rhs, "dv", ncompq*dim, CEED_EVAL_GRAD); 1014 } 1015 1016 qf_ifunction = NULL; 1017 if (problem->apply_ifunction) { // Create the Q-function that defines the action of the IFunction 1018 CeedQFunctionCreateInterior(ceed, 1, problem->apply_ifunction, 1019 problem->apply_ifunction_loc, &qf_ifunction); 1020 CeedQFunctionAddInput(qf_ifunction, "q", ncompq, CEED_EVAL_INTERP); 1021 CeedQFunctionAddInput(qf_ifunction, "dq", ncompq*dim, CEED_EVAL_GRAD); 1022 CeedQFunctionAddInput(qf_ifunction, "qdot", ncompq, CEED_EVAL_INTERP); 1023 CeedQFunctionAddInput(qf_ifunction, "qdata", qdatasize, CEED_EVAL_NONE); 1024 CeedQFunctionAddInput(qf_ifunction, "x", ncompx, CEED_EVAL_INTERP); 1025 CeedQFunctionAddOutput(qf_ifunction, "v", ncompq, CEED_EVAL_INTERP); 1026 CeedQFunctionAddOutput(qf_ifunction, "dv", ncompq*dim, CEED_EVAL_GRAD); 1027 } 1028 1029 // Create the operator that builds the quadrature data for the NS operator 1030 CeedOperatorCreate(ceed, qf_setup, NULL, NULL, &op_setup); 1031 CeedOperatorSetField(op_setup, "dx", restrictx, basisx, CEED_VECTOR_ACTIVE); 1032 CeedOperatorSetField(op_setup, "weight", CEED_ELEMRESTRICTION_NONE, 1033 basisx, CEED_VECTOR_NONE); 1034 CeedOperatorSetField(op_setup, "qdata", restrictqdi, 1035 CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE); 1036 1037 // Create the operator that sets the ICs 1038 CeedOperatorCreate(ceed, qf_ics, NULL, NULL, &op_ics); 1039 CeedOperatorSetField(op_ics, "x", restrictx, basisxc, CEED_VECTOR_ACTIVE); 1040 CeedOperatorSetField(op_ics, "q0", restrictq, 1041 CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE); 1042 1043 CeedElemRestrictionCreateVector(restrictq, &user->qceed, NULL); 1044 CeedElemRestrictionCreateVector(restrictq, &user->qdotceed, NULL); 1045 CeedElemRestrictionCreateVector(restrictq, &user->gceed, NULL); 1046 1047 if (qf_rhs) { // Create the RHS physics operator 1048 CeedOperator op; 1049 CeedOperatorCreate(ceed, qf_rhs, NULL, NULL, &op); 1050 CeedOperatorSetField(op, "q", restrictq, basisq, CEED_VECTOR_ACTIVE); 1051 CeedOperatorSetField(op, "dq", restrictq, basisq, CEED_VECTOR_ACTIVE); 1052 CeedOperatorSetField(op, "qdata", restrictqdi, 1053 CEED_BASIS_COLLOCATED, qdata); 1054 CeedOperatorSetField(op, "x", restrictx, basisx, xcorners); 1055 CeedOperatorSetField(op, "v", restrictq, basisq, CEED_VECTOR_ACTIVE); 1056 CeedOperatorSetField(op, "dv", restrictq, basisq, CEED_VECTOR_ACTIVE); 1057 user->op_rhs = op; 1058 } 1059 1060 if (qf_ifunction) { // Create the IFunction operator 1061 CeedOperator op; 1062 CeedOperatorCreate(ceed, qf_ifunction, NULL, NULL, &op); 1063 CeedOperatorSetField(op, "q", restrictq, basisq, CEED_VECTOR_ACTIVE); 1064 CeedOperatorSetField(op, "dq", restrictq, basisq, CEED_VECTOR_ACTIVE); 1065 CeedOperatorSetField(op, "qdot", restrictq, basisq, user->qdotceed); 1066 CeedOperatorSetField(op, "qdata", restrictqdi, 1067 CEED_BASIS_COLLOCATED, qdata); 1068 CeedOperatorSetField(op, "x", restrictx, basisx, xcorners); 1069 CeedOperatorSetField(op, "v", restrictq, basisq, CEED_VECTOR_ACTIVE); 1070 CeedOperatorSetField(op, "dv", restrictq, basisq, CEED_VECTOR_ACTIVE); 1071 user->op_ifunction = op; 1072 } 1073 1074 CeedQFunctionSetContext(qf_ics, &ctxSetup, sizeof ctxSetup); 1075 CeedScalar ctxNS[8] = {lambda, mu, k, cv, cp, g, Rd}; 1076 struct Advection2dContext_ ctxAdvection2d = { 1077 .CtauS = CtauS, 1078 .strong_form = strong_form, 1079 .stabilization = stab, 1080 }; 1081 switch (problemChoice) { 1082 case NS_DENSITY_CURRENT: 1083 if (qf_rhs) CeedQFunctionSetContext(qf_rhs, &ctxNS, sizeof ctxNS); 1084 if (qf_ifunction) CeedQFunctionSetContext(qf_ifunction, &ctxNS, 1085 sizeof ctxNS); 1086 break; 1087 case NS_ADVECTION: 1088 case NS_ADVECTION2D: 1089 if (qf_rhs) CeedQFunctionSetContext(qf_rhs, &ctxAdvection2d, 1090 sizeof ctxAdvection2d); 1091 if (qf_ifunction) CeedQFunctionSetContext(qf_ifunction, &ctxAdvection2d, 1092 sizeof ctxAdvection2d); 1093 } 1094 1095 // Set up PETSc context 1096 // Set up units structure 1097 units->meter = meter; 1098 units->kilogram = kilogram; 1099 units->second = second; 1100 units->Kelvin = Kelvin; 1101 units->Pascal = Pascal; 1102 units->JperkgK = JperkgK; 1103 units->mpersquareds = mpersquareds; 1104 units->WpermK = WpermK; 1105 units->kgpercubicm = kgpercubicm; 1106 units->kgpersquaredms = kgpersquaredms; 1107 units->Joulepercubicm = Joulepercubicm; 1108 1109 // Set up user structure 1110 user->comm = comm; 1111 user->outputfreq = outputfreq; 1112 user->contsteps = contsteps; 1113 user->units = units; 1114 user->dm = dm; 1115 user->dmviz = dmviz; 1116 user->interpviz = interpviz; 1117 user->ceed = ceed; 1118 1119 // Calculate qdata and ICs 1120 // Set up state global and local vectors 1121 ierr = VecZeroEntries(Q); CHKERRQ(ierr); 1122 1123 ierr = VectorPlacePetscVec(q0ceed, Qloc); CHKERRQ(ierr); 1124 1125 // Apply Setup Ceed Operators 1126 ierr = VectorPlacePetscVec(xcorners, Xloc); CHKERRQ(ierr); 1127 CeedOperatorApply(op_setup, xcorners, qdata, CEED_REQUEST_IMMEDIATE); 1128 ierr = ComputeLumpedMassMatrix(ceed, dm, restrictq, basisq, restrictqdi, qdata, 1129 user->M); CHKERRQ(ierr); 1130 1131 ierr = ICs_PetscMultiplicity(op_ics, xcorners, q0ceed, dm, Qloc, Q, restrictq, 1132 &ctxSetup, 0.0); 1133 if (1) { // Record boundary values from initial condition and override DMPlexInsertBoundaryValues() 1134 // We use this for the main simulation DM because the reference DMPlexInsertBoundaryValues() is very slow. If we 1135 // disable this, we should still get the same results due to the problem->bc function, but with potentially much 1136 // slower execution. 1137 Vec Qbc; 1138 ierr = DMGetNamedLocalVector(dm, "Qbc", &Qbc); CHKERRQ(ierr); 1139 ierr = VecCopy(Qloc, Qbc); CHKERRQ(ierr); 1140 ierr = VecZeroEntries(Qloc); CHKERRQ(ierr); 1141 ierr = DMGlobalToLocal(dm, Q, INSERT_VALUES, Qloc); CHKERRQ(ierr); 1142 ierr = VecAXPY(Qbc, -1., Qloc); CHKERRQ(ierr); 1143 ierr = DMRestoreNamedLocalVector(dm, "Qbc", &Qbc); CHKERRQ(ierr); 1144 ierr = PetscObjectComposeFunction((PetscObject)dm, 1145 "DMPlexInsertBoundaryValues_C",DMPlexInsertBoundaryValues_NS); CHKERRQ(ierr); 1146 } 1147 1148 MPI_Comm_rank(comm, &rank); 1149 if (!rank) {ierr = PetscMkdir(user->outputfolder); CHKERRQ(ierr);} 1150 // Gather initial Q values 1151 // In case of continuation of simulation, set up initial values from binary file 1152 if (contsteps) { // continue from existent solution 1153 PetscViewer viewer; 1154 char filepath[PETSC_MAX_PATH_LEN]; 1155 // Read input 1156 ierr = PetscSNPrintf(filepath, sizeof filepath, "%s/ns-solution.bin", 1157 user->outputfolder); 1158 CHKERRQ(ierr); 1159 ierr = PetscViewerBinaryOpen(comm, filepath, FILE_MODE_READ, &viewer); 1160 CHKERRQ(ierr); 1161 ierr = VecLoad(Q, viewer); CHKERRQ(ierr); 1162 ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); 1163 } else { 1164 //ierr = DMLocalToGlobal(dm, Qloc, INSERT_VALUES, Q);CHKERRQ(ierr); 1165 } 1166 ierr = DMRestoreLocalVector(dm, &Qloc); CHKERRQ(ierr); 1167 1168 // Create and setup TS 1169 ierr = TSCreate(comm, &ts); CHKERRQ(ierr); 1170 ierr = TSSetDM(ts, dm); CHKERRQ(ierr); 1171 if (implicit) { 1172 ierr = TSSetType(ts, TSBDF); CHKERRQ(ierr); 1173 if (user->op_ifunction) { 1174 ierr = TSSetIFunction(ts, NULL, IFunction_NS, &user); CHKERRQ(ierr); 1175 } else { // Implicit integrators can fall back to using an RHSFunction 1176 ierr = TSSetRHSFunction(ts, NULL, RHS_NS, &user); CHKERRQ(ierr); 1177 } 1178 } else { 1179 if (!user->op_rhs) SETERRQ(comm,PETSC_ERR_ARG_NULL, 1180 "Problem does not provide RHSFunction"); 1181 ierr = TSSetType(ts, TSRK); CHKERRQ(ierr); 1182 ierr = TSRKSetType(ts, TSRK5F); CHKERRQ(ierr); 1183 ierr = TSSetRHSFunction(ts, NULL, RHS_NS, &user); CHKERRQ(ierr); 1184 } 1185 ierr = TSSetMaxTime(ts, 500. * units->second); CHKERRQ(ierr); 1186 ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_STEPOVER); CHKERRQ(ierr); 1187 ierr = TSSetTimeStep(ts, 1.e-2 * units->second); CHKERRQ(ierr); 1188 if (test) {ierr = TSSetMaxSteps(ts, 1); CHKERRQ(ierr);} 1189 ierr = TSGetAdapt(ts, &adapt); CHKERRQ(ierr); 1190 ierr = TSAdaptSetStepLimits(adapt, 1191 1.e-12 * units->second, 1192 1.e2 * units->second); CHKERRQ(ierr); 1193 ierr = TSSetFromOptions(ts); CHKERRQ(ierr); 1194 if (!contsteps) { // print initial condition 1195 if (!test) { 1196 ierr = TSMonitor_NS(ts, 0, 0., Q, user); CHKERRQ(ierr); 1197 } 1198 } else { // continue from time of last output 1199 PetscReal time; 1200 PetscInt count; 1201 PetscViewer viewer; 1202 char filepath[PETSC_MAX_PATH_LEN]; 1203 ierr = PetscSNPrintf(filepath, sizeof filepath, "%s/ns-time.bin", 1204 user->outputfolder); CHKERRQ(ierr); 1205 ierr = PetscViewerBinaryOpen(comm, filepath, FILE_MODE_READ, &viewer); 1206 CHKERRQ(ierr); 1207 ierr = PetscViewerBinaryRead(viewer, &time, 1, &count, PETSC_REAL); 1208 CHKERRQ(ierr); 1209 ierr = PetscViewerDestroy(&viewer); CHKERRQ(ierr); 1210 ierr = TSSetTime(ts, time * user->units->second); CHKERRQ(ierr); 1211 } 1212 if (!test) { 1213 ierr = TSMonitorSet(ts, TSMonitor_NS, user, NULL); CHKERRQ(ierr); 1214 } 1215 1216 // Solve 1217 start = MPI_Wtime(); 1218 ierr = PetscBarrier((PetscObject)ts); CHKERRQ(ierr); 1219 ierr = TSSolve(ts, Q); CHKERRQ(ierr); 1220 cpu_time_used = MPI_Wtime() - start; 1221 ierr = TSGetSolveTime(ts,&ftime); CHKERRQ(ierr); 1222 ierr = MPI_Allreduce(MPI_IN_PLACE, &cpu_time_used, 1, MPI_DOUBLE, MPI_MIN, 1223 comm); CHKERRQ(ierr); 1224 if (!test) { 1225 ierr = PetscPrintf(PETSC_COMM_WORLD, 1226 "Time taken for solution: %g\n", 1227 (double)cpu_time_used); CHKERRQ(ierr); 1228 } 1229 1230 // Get error 1231 if (problem->non_zero_time && !test) { 1232 Vec Qexact, Qexactloc; 1233 PetscReal norm; 1234 ierr = DMCreateGlobalVector(dm, &Qexact); CHKERRQ(ierr); 1235 ierr = DMGetLocalVector(dm, &Qexactloc); CHKERRQ(ierr); 1236 ierr = VecGetSize(Qexactloc, &lnodes); CHKERRQ(ierr); 1237 1238 ierr = ICs_PetscMultiplicity(op_ics, xcorners, q0ceed, dm, Qexactloc, Qexact, 1239 restrictq, &ctxSetup, ftime); CHKERRQ(ierr); 1240 1241 ierr = VecAXPY(Q, -1.0, Qexact); CHKERRQ(ierr); 1242 ierr = VecNorm(Q, NORM_MAX, &norm); CHKERRQ(ierr); 1243 CeedVectorDestroy(&q0ceed); 1244 ierr = PetscPrintf(PETSC_COMM_WORLD, 1245 "Max Error: %g\n", 1246 (double)norm); CHKERRQ(ierr); 1247 } 1248 1249 // Output Statistics 1250 ierr = TSGetStepNumber(ts,&steps); CHKERRQ(ierr); 1251 if (!test) { 1252 ierr = PetscPrintf(PETSC_COMM_WORLD, 1253 "Time integrator took %D time steps to reach final time %g\n", 1254 steps,(double)ftime); CHKERRQ(ierr); 1255 } 1256 1257 // Clean up libCEED 1258 CeedVectorDestroy(&qdata); 1259 CeedVectorDestroy(&user->qceed); 1260 CeedVectorDestroy(&user->qdotceed); 1261 CeedVectorDestroy(&user->gceed); 1262 CeedVectorDestroy(&xcorners); 1263 CeedBasisDestroy(&basisq); 1264 CeedBasisDestroy(&basisx); 1265 CeedBasisDestroy(&basisxc); 1266 CeedElemRestrictionDestroy(&restrictq); 1267 CeedElemRestrictionDestroy(&restrictx); 1268 CeedElemRestrictionDestroy(&restrictqdi); 1269 CeedQFunctionDestroy(&qf_setup); 1270 CeedQFunctionDestroy(&qf_ics); 1271 CeedQFunctionDestroy(&qf_rhs); 1272 CeedQFunctionDestroy(&qf_ifunction); 1273 CeedOperatorDestroy(&op_setup); 1274 CeedOperatorDestroy(&op_ics); 1275 CeedOperatorDestroy(&user->op_rhs); 1276 CeedOperatorDestroy(&user->op_ifunction); 1277 CeedDestroy(&ceed); 1278 1279 // Clean up PETSc 1280 ierr = VecDestroy(&Q); CHKERRQ(ierr); 1281 ierr = VecDestroy(&user->M); CHKERRQ(ierr); 1282 ierr = MatDestroy(&interpviz); CHKERRQ(ierr); 1283 ierr = DMDestroy(&dmviz); CHKERRQ(ierr); 1284 ierr = TSDestroy(&ts); CHKERRQ(ierr); 1285 ierr = DMDestroy(&dm); CHKERRQ(ierr); 1286 ierr = PetscFree(units); CHKERRQ(ierr); 1287 ierr = PetscFree(user); CHKERRQ(ierr); 1288 return PetscFinalize(); 1289 } 1290 1291