Actual source code: swarm.c

  1: #include "petscdmswarm.h"
  2: #include <petsc/private/dmswarmimpl.h>
  3: #include <petsc/private/hashsetij.h>
  4: #include <petsc/private/petscfeimpl.h>
  5: #include <petscviewer.h>
  6: #include <petscdraw.h>
  7: #include <petscdmplex.h>
  8: #include <petscblaslapack.h>
  9: #include "../src/dm/impls/swarm/data_bucket.h"
 10: #include <petscdmlabel.h>
 11: #include <petscsection.h>

 13: PetscLogEvent DMSWARM_Migrate, DMSWARM_SetSizes, DMSWARM_AddPoints, DMSWARM_RemovePoints, DMSWARM_Sort;
 14: PetscLogEvent DMSWARM_DataExchangerTopologySetup, DMSWARM_DataExchangerBegin, DMSWARM_DataExchangerEnd;
 15: PetscLogEvent DMSWARM_DataExchangerSendCount, DMSWARM_DataExchangerPack;

 17: const char *DMSwarmTypeNames[]          = {"basic", "pic", NULL};
 18: const char *DMSwarmMigrateTypeNames[]   = {"basic", "dmcellnscatter", "dmcellexact", "user", NULL};
 19: const char *DMSwarmCollectTypeNames[]   = {"basic", "boundingbox", "general", "user", NULL};
 20: const char *DMSwarmRemapTypeNames[]     = {"none", "pfak", "colella", "DMSwarmRemapType", "DMSWARM_REMAP_", NULL};
 21: const char *DMSwarmPICLayoutTypeNames[] = {"regular", "gauss", "subdivision", NULL};

 23: const char DMSwarmField_pid[]     = "DMSwarm_pid";
 24: const char DMSwarmField_rank[]    = "DMSwarm_rank";
 25: const char DMSwarmPICField_coor[] = "DMSwarmPIC_coor";

 27: PetscInt SwarmDataFieldId = -1;

 29: #if PetscDefined(HAVE_HDF5)
 30: #include <petscviewerhdf5.h>

 32: static PetscErrorCode VecView_Swarm_HDF5_Internal(Vec v, PetscViewer viewer)
 33: {
 34:   DM        dm;
 35:   PetscReal seqval;
 36:   PetscInt  seqnum, bs;
 37:   PetscBool isseq, ists;

 39:   PetscFunctionBegin;
 40:   PetscCall(VecGetDM(v, &dm));
 41:   PetscCall(VecGetBlockSize(v, &bs));
 42:   PetscCall(PetscViewerHDF5PushGroup(viewer, "/particle_fields"));
 43:   PetscCall(PetscObjectTypeCompare((PetscObject)v, VECSEQ, &isseq));
 44:   PetscCall(DMGetOutputSequenceNumber(dm, &seqnum, &seqval));
 45:   PetscCall(PetscViewerHDF5IsTimestepping(viewer, &ists));
 46:   if (ists) PetscCall(PetscViewerHDF5SetTimestep(viewer, seqnum));
 47:   /* PetscCall(DMSequenceView_HDF5(dm, "time", seqnum, (PetscScalar) seqval, viewer)); */
 48:   PetscCall(VecViewNative(v, viewer));
 49:   PetscCall(PetscViewerHDF5WriteObjectAttribute(viewer, (PetscObject)v, "Nc", PETSC_INT, (void *)&bs));
 50:   PetscCall(PetscViewerHDF5PopGroup(viewer));
 51:   PetscFunctionReturn(PETSC_SUCCESS);
 52: }

 54: static PetscErrorCode DMSwarmView_HDF5(DM dm, PetscViewer viewer)
 55: {
 56:   DMSwarmCellDM celldm;
 57:   Vec           coordinates;
 58:   PetscInt      Np, Nfc;
 59:   PetscBool     isseq;
 60:   const char  **coordFields;

 62:   PetscFunctionBegin;
 63:   PetscCall(DMSwarmGetCellDMActive(dm, &celldm));
 64:   PetscCall(DMSwarmCellDMGetCoordinateFields(celldm, &Nfc, &coordFields));
 65:   PetscCheck(Nfc == 1, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "We only support a single coordinate field right now, not %" PetscInt_FMT, Nfc);
 66:   PetscCall(DMSwarmGetSize(dm, &Np));
 67:   PetscCall(DMSwarmCreateGlobalVectorFromField(dm, coordFields[0], &coordinates));
 68:   PetscCall(PetscObjectSetName((PetscObject)coordinates, "coordinates"));
 69:   PetscCall(PetscViewerHDF5PushGroup(viewer, "/particles"));
 70:   PetscCall(PetscObjectTypeCompare((PetscObject)coordinates, VECSEQ, &isseq));
 71:   PetscCall(VecViewNative(coordinates, viewer));
 72:   PetscCall(PetscViewerHDF5WriteObjectAttribute(viewer, (PetscObject)coordinates, "Np", PETSC_INT, (void *)&Np));
 73:   PetscCall(PetscViewerHDF5PopGroup(viewer));
 74:   PetscCall(DMSwarmDestroyGlobalVectorFromField(dm, coordFields[0], &coordinates));
 75:   PetscFunctionReturn(PETSC_SUCCESS);
 76: }
 77: #endif

 79: static PetscErrorCode VecView_Swarm(Vec v, PetscViewer viewer)
 80: {
 81:   DM dm;
 82: #if PetscDefined(HAVE_HDF5)
 83:   PetscBool ishdf5;
 84: #endif

 86:   PetscFunctionBegin;
 87:   PetscCall(VecGetDM(v, &dm));
 88:   PetscCheck(dm, PetscObjectComm((PetscObject)v), PETSC_ERR_ARG_WRONG, "Vector not generated from a DM");
 89: #if PetscDefined(HAVE_HDF5)
 90:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
 91:   if (ishdf5) {
 92:     PetscCall(VecView_Swarm_HDF5_Internal(v, viewer));
 93:     PetscFunctionReturn(PETSC_SUCCESS);
 94:   }
 95: #endif
 96:   PetscCall(VecViewNative(v, viewer));
 97:   PetscFunctionReturn(PETSC_SUCCESS);
 98: }

100: /*@
101:   DMSwarmVectorGetField - Gets the fields from which to define a `Vec` object
102:   when `DMCreateLocalVector()`, or `DMCreateGlobalVector()` is called

104:   Not collective

106:   Input Parameter:
107: . sw - a `DMSWARM`

109:   Output Parameters:
110: + Nf         - the number of fields
111: - fieldnames - the textual name given to each registered field, or NULL if it has not been set

113:   Level: beginner

115: .seealso: `DM`, `DMSWARM`, `DMSwarmVectorDefineField()`, `DMSwarmRegisterPetscDatatypeField()`, `DMCreateGlobalVector()`, `DMCreateLocalVector()`
116: @*/
117: PetscErrorCode DMSwarmVectorGetField(DM sw, PetscInt *Nf, const char **fieldnames[])
118: {
119:   DMSwarmCellDM celldm;

121:   PetscFunctionBegin;
123:   PetscCall(DMSwarmGetCellDMActive(sw, &celldm));
124:   PetscCall(DMSwarmCellDMGetFields(celldm, Nf, fieldnames));
125:   PetscFunctionReturn(PETSC_SUCCESS);
126: }

128: /*@
129:   DMSwarmVectorDefineField - Sets the field from which to define a `Vec` object
130:   when `DMCreateLocalVector()`, or `DMCreateGlobalVector()` is called

132:   Collective

134:   Input Parameters:
135: + dm        - a `DMSWARM`
136: - fieldname - the textual name given to each registered field

138:   Level: beginner

140:   Notes:
141:   The field with name `fieldname` must have data type `PETSC_REAL` or `PETSC_SCALAR`.

143:   This function must be called prior to calling `DMCreateLocalVector()`, `DMCreateGlobalVector()`.
144:   Multiple calls to `DMSwarmVectorDefineField()` are permitted.

146: .seealso: `DM`, `DMSWARM`, `DMSwarmVectorDefineFields()`, `DMSwarmVectorGetField()`, `DMSwarmRegisterPetscDatatypeField()`, `DMCreateGlobalVector()`, `DMCreateLocalVector()`
147: @*/
148: PetscErrorCode DMSwarmVectorDefineField(DM dm, const char fieldname[])
149: {
150:   PetscFunctionBegin;
151:   PetscCall(DMSwarmVectorDefineFields(dm, 1, &fieldname));
152:   PetscFunctionReturn(PETSC_SUCCESS);
153: }

155: /*@
156:   DMSwarmVectorDefineFields - Sets the fields from which to define a `Vec` object
157:   when `DMCreateLocalVector()`, or `DMCreateGlobalVector()` is called

159:   Collective, No Fortran support

161:   Input Parameters:
162: + sw         - a `DMSWARM`
163: . Nf         - the number of fields
164: - fieldnames - the textual name given to each registered field

166:   Level: beginner

168:   Notes:
169:   Each field with name in `fieldnames` must have data type `PETSC_REAL` or `PETSC_SCALAR`.

171:   This function must be called prior to calling `DMCreateLocalVector()`, `DMCreateGlobalVector()`.
172:   Multiple calls to `DMSwarmVectorDefineField()` are permitted.

174: .seealso: `DM`, `DMSWARM`, `DMSwarmVectorDefineField()`, `DMSwarmVectorGetField()`, `DMSwarmRegisterPetscDatatypeField()`, `DMCreateGlobalVector()`, `DMCreateLocalVector()`
175: @*/
176: PetscErrorCode DMSwarmVectorDefineFields(DM sw, PetscInt Nf, const char *fieldnames[])
177: {
178:   DM_Swarm     *swarm = (DM_Swarm *)sw->data;
179:   DMSwarmCellDM celldm;

181:   PetscFunctionBegin;
183:   if (fieldnames) PetscAssertPointer(fieldnames, 3);
184:   if (!swarm->issetup) PetscCall(DMSetUp(sw));
185:   PetscCheck(Nf >= 0, PetscObjectComm((PetscObject)sw), PETSC_ERR_ARG_OUTOFRANGE, "Number of fields must be non-negative, not %" PetscInt_FMT, Nf);
186:   for (PetscInt f = 0; f < Nf; ++f) {
187:     PetscDataType type;

189:     PetscCall(DMSwarmGetFieldInfo(sw, fieldnames[f], NULL, &type));
190:     PetscCheck(type == PETSC_REAL || type == PETSC_SCALAR, PetscObjectComm((PetscObject)sw), PETSC_ERR_SUP, "Field %s must have type PETSC_REAL or PETSC_SCALAR, not %s", fieldnames[f], PetscDataTypes[type]);
191:   }
192:   // Create a dummy cell DM if none has been specified (I think we should not support this mode)
193:   if (!swarm->activeCellDM) {
194:     DM            dm;
195:     DMSwarmCellDM celldm;

197:     PetscCall(DMCreate(PetscObjectComm((PetscObject)sw), &dm));
198:     PetscCall(DMSetType(dm, DMSHELL));
199:     PetscCall(PetscObjectSetName((PetscObject)dm, "dummy"));
200:     PetscCall(DMSwarmCellDMCreate(dm, 0, NULL, 0, NULL, &celldm));
201:     PetscCall(DMDestroy(&dm));
202:     PetscCall(DMSwarmAddCellDM(sw, celldm));
203:     PetscCall(DMSwarmCellDMDestroy(&celldm));
204:     PetscCall(DMSwarmSetCellDMActive(sw, "dummy"));
205:   }
206:   PetscCall(DMSwarmGetCellDMActive(sw, &celldm));
207:   for (PetscInt f = 0; f < celldm->Nf; ++f) PetscCall(PetscFree(celldm->dmFields[f]));
208:   PetscCall(PetscFree(celldm->dmFields));

210:   celldm->Nf = Nf;
211:   PetscCall(PetscMalloc1(Nf, &celldm->dmFields));
212:   for (PetscInt f = 0; f < Nf; ++f) PetscCall(PetscStrallocpy(fieldnames[f], (char **)&celldm->dmFields[f]));
213:   PetscFunctionReturn(PETSC_SUCCESS);
214: }

216: /* requires DMSwarmDefineFieldVector has been called */
217: static PetscErrorCode DMCreateGlobalVector_Swarm(DM sw, Vec *vec)
218: {
219:   DM_Swarm     *swarm = (DM_Swarm *)sw->data;
220:   DMSwarmCellDM celldm;
221:   Vec           x;
222:   char          name[PETSC_MAX_PATH_LEN];
223:   PetscInt      bs = 0, n;

225:   PetscFunctionBegin;
226:   if (!swarm->issetup) PetscCall(DMSetUp(sw));
227:   PetscCall(DMSwarmGetCellDMActive(sw, &celldm));
228:   PetscCheck(celldm->Nf, PetscObjectComm((PetscObject)sw), PETSC_ERR_USER, "Active cell DM does not define any fields");
229:   PetscCall(DMSwarmDataBucketGetSizes(swarm->db, &n, NULL, NULL));

231:   PetscCall(PetscStrncpy(name, "DMSwarmField", PETSC_MAX_PATH_LEN));
232:   for (PetscInt f = 0; f < celldm->Nf; ++f) {
233:     PetscInt fbs;
234:     PetscCall(PetscStrlcat(name, "_", PETSC_MAX_PATH_LEN));
235:     PetscCall(PetscStrlcat(name, celldm->dmFields[f], PETSC_MAX_PATH_LEN));
236:     PetscCall(DMSwarmGetFieldInfo(sw, celldm->dmFields[f], &fbs, NULL));
237:     bs += fbs;
238:   }
239:   PetscCall(VecCreate(PetscObjectComm((PetscObject)sw), &x));
240:   PetscCall(PetscObjectSetName((PetscObject)x, name));
241:   PetscCall(VecSetSizes(x, n * bs, PETSC_DETERMINE));
242:   PetscCall(VecSetBlockSize(x, bs));
243:   PetscCall(VecSetDM(x, sw));
244:   PetscCall(VecSetFromOptions(x));
245:   PetscCall(VecSetOperation(x, VECOP_VIEW, (PetscErrorCodeFn *)VecView_Swarm));
246:   *vec = x;
247:   PetscFunctionReturn(PETSC_SUCCESS);
248: }

250: /* requires DMSwarmDefineFieldVector has been called */
251: static PetscErrorCode DMCreateLocalVector_Swarm(DM sw, Vec *vec)
252: {
253:   DM_Swarm     *swarm = (DM_Swarm *)sw->data;
254:   DMSwarmCellDM celldm;
255:   Vec           x;
256:   char          name[PETSC_MAX_PATH_LEN];
257:   PetscInt      bs = 0, n;

259:   PetscFunctionBegin;
260:   if (!swarm->issetup) PetscCall(DMSetUp(sw));
261:   PetscCall(DMSwarmGetCellDMActive(sw, &celldm));
262:   PetscCheck(celldm->Nf, PetscObjectComm((PetscObject)sw), PETSC_ERR_USER, "Active cell DM does not define any fields");
263:   PetscCall(DMSwarmDataBucketGetSizes(swarm->db, &n, NULL, NULL));

265:   PetscCall(PetscStrncpy(name, "DMSwarmField", PETSC_MAX_PATH_LEN));
266:   for (PetscInt f = 0; f < celldm->Nf; ++f) {
267:     PetscInt fbs;
268:     PetscCall(PetscStrlcat(name, "_", PETSC_MAX_PATH_LEN));
269:     PetscCall(PetscStrlcat(name, celldm->dmFields[f], PETSC_MAX_PATH_LEN));
270:     PetscCall(DMSwarmGetFieldInfo(sw, celldm->dmFields[f], &fbs, NULL));
271:     bs += fbs;
272:   }
273:   PetscCall(VecCreate(PETSC_COMM_SELF, &x));
274:   PetscCall(PetscObjectSetName((PetscObject)x, name));
275:   PetscCall(VecSetSizes(x, n * bs, PETSC_DETERMINE));
276:   PetscCall(VecSetBlockSize(x, bs));
277:   PetscCall(VecSetDM(x, sw));
278:   PetscCall(VecSetFromOptions(x));
279:   *vec = x;
280:   PetscFunctionReturn(PETSC_SUCCESS);
281: }

283: static PetscErrorCode DMSwarmDestroyVectorFromField_Private(DM dm, const char fieldname[], Vec *vec)
284: {
285:   DM_Swarm        *swarm = (DM_Swarm *)dm->data;
286:   DMSwarmDataField gfield;
287:   PetscInt         bs, nlocal, fid = -1, cfid = -2;
288:   PetscBool        flg;

290:   PetscFunctionBegin;
291:   /* check vector is an inplace array */
292:   PetscCall(DMSwarmDataBucketGetDMSwarmDataFieldIdByName(swarm->db, fieldname, &fid));
293:   PetscCall(PetscObjectComposedDataGetInt((PetscObject)*vec, SwarmDataFieldId, cfid, flg));
294:   (void)flg; /* avoid compiler warning */
295:   PetscCheck(cfid == fid, PetscObjectComm((PetscObject)dm), PETSC_ERR_USER, "Vector being destroyed was not created from DMSwarm field(%s)! %" PetscInt_FMT " != %" PetscInt_FMT, fieldname, cfid, fid);
296:   PetscCall(VecGetLocalSize(*vec, &nlocal));
297:   PetscCall(VecGetBlockSize(*vec, &bs));
298:   PetscCheck(nlocal / bs == swarm->db->L, PetscObjectComm((PetscObject)dm), PETSC_ERR_USER, "DMSwarm sizes have changed since vector was created - cannot ensure pointers are valid");
299:   PetscCall(DMSwarmDataBucketGetDMSwarmDataFieldByName(swarm->db, fieldname, &gfield));
300:   PetscCall(DMSwarmDataFieldRestoreAccess(gfield));
301:   PetscCall(VecResetArray(*vec));
302:   PetscCall(VecDestroy(vec));
303:   PetscFunctionReturn(PETSC_SUCCESS);
304: }

306: static PetscErrorCode DMSwarmCreateVectorFromField_Private(DM dm, const char fieldname[], MPI_Comm comm, Vec *vec)
307: {
308:   DM_Swarm     *swarm = (DM_Swarm *)dm->data;
309:   PetscDataType type;
310:   PetscScalar  *array;
311:   PetscInt      bs, n, fid;
312:   char          name[PETSC_MAX_PATH_LEN];
313:   PetscMPIInt   size;
314:   PetscBool     iscuda, iskokkos, iship;

316:   PetscFunctionBegin;
317:   if (!swarm->issetup) PetscCall(DMSetUp(dm));
318:   PetscCall(DMSwarmDataBucketGetSizes(swarm->db, &n, NULL, NULL));
319:   PetscCall(DMSwarmGetFieldInfo(dm, fieldname, &bs, &type));
320:   PetscCheck(type == PETSC_SCALAR, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Field %s must have type PETSC_SCALAR, not %s", fieldname, PetscDataTypes[type]);
321:   PetscCall(DMSwarmGetField(dm, fieldname, NULL, NULL, (void **)&array));

323:   PetscCallMPI(MPI_Comm_size(comm, &size));
324:   PetscCall(PetscStrcmp(dm->vectype, VECKOKKOS, &iskokkos));
325:   PetscCall(PetscStrcmp(dm->vectype, VECCUDA, &iscuda));
326:   PetscCall(PetscStrcmp(dm->vectype, VECHIP, &iship));
327:   PetscCall(VecCreate(comm, vec));
328:   PetscCall(VecSetSizes(*vec, n * bs, PETSC_DETERMINE));
329:   PetscCall(VecSetBlockSize(*vec, bs));
330:   if (iskokkos) PetscCall(VecSetType(*vec, VECKOKKOS));
331:   else if (iscuda) PetscCall(VecSetType(*vec, VECCUDA));
332:   else if (iship) PetscCall(VecSetType(*vec, VECHIP));
333:   else PetscCall(VecSetType(*vec, VECSTANDARD));
334:   PetscCall(VecPlaceArray(*vec, array));

336:   PetscCall(PetscSNPrintf(name, PETSC_MAX_PATH_LEN - 1, "DMSwarmSharedField_%s", fieldname));
337:   PetscCall(PetscObjectSetName((PetscObject)*vec, name));

339:   /* Set guard */
340:   PetscCall(DMSwarmDataBucketGetDMSwarmDataFieldIdByName(swarm->db, fieldname, &fid));
341:   PetscCall(PetscObjectComposedDataSetInt((PetscObject)*vec, SwarmDataFieldId, fid));

343:   PetscCall(VecSetDM(*vec, dm));
344:   PetscCall(VecSetOperation(*vec, VECOP_VIEW, (PetscErrorCodeFn *)VecView_Swarm));
345:   PetscFunctionReturn(PETSC_SUCCESS);
346: }

348: static PetscErrorCode DMSwarmDestroyVectorFromFields_Private(DM sw, PetscInt Nf, const char *fieldnames[], Vec *vec)
349: {
350:   DM_Swarm          *swarm = (DM_Swarm *)sw->data;
351:   const PetscScalar *array;
352:   PetscInt           bs, n, id = 0, cid = -2;
353:   PetscBool          flg;

355:   PetscFunctionBegin;
356:   for (PetscInt f = 0; f < Nf; ++f) {
357:     PetscInt fid;

359:     PetscCall(DMSwarmDataBucketGetDMSwarmDataFieldIdByName(swarm->db, fieldnames[f], &fid));
360:     id += fid;
361:   }
362:   PetscCall(PetscObjectComposedDataGetInt((PetscObject)*vec, SwarmDataFieldId, cid, flg));
363:   (void)flg; /* avoid compiler warning */
364:   PetscCheck(cid == id, PetscObjectComm((PetscObject)sw), PETSC_ERR_USER, "Vector being destroyed was not created from DMSwarm field(%s)! %" PetscInt_FMT " != %" PetscInt_FMT, fieldnames[0], cid, id);
365:   PetscCall(VecGetLocalSize(*vec, &n));
366:   PetscCall(VecGetBlockSize(*vec, &bs));
367:   n /= bs;
368:   PetscCheck(n == swarm->db->L, PetscObjectComm((PetscObject)sw), PETSC_ERR_USER, "DMSwarm sizes have changed since vector was created - cannot ensure pointers are valid");
369:   PetscCall(VecGetArrayRead(*vec, &array));
370:   for (PetscInt f = 0, off = 0; f < Nf; ++f) {
371:     void         *farray;
372:     PetscDataType ftype;
373:     PetscInt      fbs;

375:     PetscCall(DMSwarmGetFieldInfo(sw, fieldnames[f], &fbs, &ftype));
376:     PetscCheck(ftype == PETSC_REAL || ftype == PETSC_SCALAR, PetscObjectComm((PetscObject)sw), PETSC_ERR_SUP, "Field %s must have type PETSC_REAL or PETSC_SCALAR, not %s", fieldnames[f], PetscDataTypes[ftype]);
377:     PetscCall(DMSwarmGetField(sw, fieldnames[f], NULL, NULL, &farray));
378:     PetscCheck(off + fbs <= bs, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Invalid blocksize %" PetscInt_FMT " < %" PetscInt_FMT, bs, off + fbs);
379:     if (ftype == PETSC_REAL) {
380:       PetscReal *rarray = (PetscReal *)farray;

382:       for (PetscInt i = 0; i < n; ++i) {
383:         for (PetscInt b = 0; b < fbs; ++b) rarray[i * fbs + b] = PetscRealPart(array[i * bs + off + b]);
384:       }
385:     } else {
386:       PetscScalar *sarray = (PetscScalar *)farray;

388:       for (PetscInt i = 0; i < n; ++i) {
389:         for (PetscInt b = 0; b < fbs; ++b) sarray[i * fbs + b] = array[i * bs + off + b];
390:       }
391:     }
392:     off += fbs;
393:     PetscCall(DMSwarmRestoreField(sw, fieldnames[f], NULL, NULL, &farray));
394:   }
395:   PetscCall(VecRestoreArrayRead(*vec, &array));
396:   PetscCall(VecDestroy(vec));
397:   PetscFunctionReturn(PETSC_SUCCESS);
398: }

400: static PetscErrorCode DMSwarmCreateVectorFromFields_Private(DM sw, PetscInt Nf, const char *fieldnames[], MPI_Comm comm, Vec *vec)
401: {
402:   DM_Swarm    *swarm = (DM_Swarm *)sw->data;
403:   PetscScalar *array;
404:   PetscInt     n, bs = 0, id = 0;
405:   char         name[PETSC_MAX_PATH_LEN];

407:   PetscFunctionBegin;
408:   if (!swarm->issetup) PetscCall(DMSetUp(sw));
409:   PetscCall(DMSwarmDataBucketGetSizes(swarm->db, &n, NULL, NULL));
410:   for (PetscInt f = 0; f < Nf; ++f) {
411:     PetscDataType ftype;
412:     PetscInt      fbs;

414:     PetscCall(DMSwarmGetFieldInfo(sw, fieldnames[f], &fbs, &ftype));
415:     PetscCheck(ftype == PETSC_REAL || ftype == PETSC_SCALAR, PetscObjectComm((PetscObject)sw), PETSC_ERR_SUP, "Field %s must have type PETSC_REAL or PETSC_SCALAR, not %s", fieldnames[f], PetscDataTypes[ftype]);
416:     bs += fbs;
417:   }

419:   PetscCall(VecCreate(comm, vec));
420:   PetscCall(VecSetSizes(*vec, n * bs, PETSC_DETERMINE));
421:   PetscCall(VecSetBlockSize(*vec, bs));
422:   PetscCall(VecSetType(*vec, sw->vectype));

424:   PetscCall(VecGetArrayWrite(*vec, &array));
425:   for (PetscInt f = 0, off = 0; f < Nf; ++f) {
426:     void         *farray;
427:     PetscDataType ftype;
428:     PetscInt      fbs;

430:     PetscCall(DMSwarmGetField(sw, fieldnames[f], &fbs, &ftype, &farray));
431:     if (ftype == PETSC_REAL) {
432:       const PetscReal *rarray = (const PetscReal *)farray;

434:       for (PetscInt i = 0; i < n; ++i) {
435:         for (PetscInt b = 0; b < fbs; ++b) array[i * bs + off + b] = rarray[i * fbs + b];
436:       }
437:     } else {
438:       const PetscScalar *sarray = (const PetscScalar *)farray;

440:       for (PetscInt i = 0; i < n; ++i) {
441:         for (PetscInt b = 0; b < fbs; ++b) array[i * bs + off + b] = sarray[i * fbs + b];
442:       }
443:     }
444:     off += fbs;
445:     PetscCall(DMSwarmRestoreField(sw, fieldnames[f], &fbs, &ftype, &farray));
446:   }
447:   PetscCall(VecRestoreArrayWrite(*vec, &array));

449:   PetscCall(PetscStrncpy(name, "DMSwarmField", PETSC_MAX_PATH_LEN));
450:   for (PetscInt f = 0; f < Nf; ++f) {
451:     PetscCall(PetscStrlcat(name, "_", PETSC_MAX_PATH_LEN));
452:     PetscCall(PetscStrlcat(name, fieldnames[f], PETSC_MAX_PATH_LEN));
453:   }
454:   PetscCall(PetscObjectSetName((PetscObject)*vec, name));

456:   for (PetscInt f = 0; f < Nf; ++f) {
457:     PetscInt fid;

459:     PetscCall(DMSwarmDataBucketGetDMSwarmDataFieldIdByName(swarm->db, fieldnames[f], &fid));
460:     id += fid;
461:   }
462:   PetscCall(PetscObjectComposedDataSetInt((PetscObject)*vec, SwarmDataFieldId, id));

464:   PetscCall(VecSetDM(*vec, sw));
465:   PetscCall(VecSetOperation(*vec, VECOP_VIEW, (PetscErrorCodeFn *)VecView_Swarm));
466:   PetscFunctionReturn(PETSC_SUCCESS);
467: }

469: /*@
470:   DMSwarmPreallocateMassMatrix - Preallocate particle mass matrix between a `DMSWARM` and a `DMPLEX`

472:   Collective

474:   Input Parameters:
475: + dmc    - The `DMSWARM` object
476: . dmf    - The `DMPLEX` object
477: . mass   - The mass matrix to preallocate
478: . rStart - The starting row index for this process
479: . maxC   - The maximum number of columns per row
480: - ctx    - The user context

482:   Level: developer

484: .seealso: [](ch_unstructured), `DM`, `DMSWARM`, `DMPLEX`, `DMCreateMassMatrix()`, `DMSwarmFillMassMatrix()`
485: @*/
486: PetscErrorCode DMSwarmPreallocateMassMatrix(DM dmc, DM dmf, Mat mass, PetscInt *rStart, PetscInt *maxC, PetscCtx ctx)
487: {
488:   MPI_Comm     comm;
489:   PetscHSetIJ  ht;
490:   PetscDS      ds;
491:   PetscSection fsection, globalFSection;
492:   PetscLayout  rLayout, colLayout;
493:   PetscInt    *dnz, *onz;
494:   PetscInt     cStart, cEnd, locRows, locCols, colStart, colEnd, Nf, totNc = 0;

496:   PetscFunctionBegin;
500:   PetscAssertPointer(rStart, 4);
501:   PetscAssertPointer(maxC, 5);
502:   PetscCall(PetscObjectGetComm((PetscObject)mass, &comm));
503:   PetscCall(DMPlexGetHeightStratum(dmf, 0, &cStart, &cEnd));
504:   PetscCall(DMGetLocalSection(dmf, &fsection));
505:   PetscCall(DMGetGlobalSection(dmf, &globalFSection));
506:   PetscCall(DMGetDS(dmf, &ds));
507:   PetscCall(PetscDSGetNumFields(ds, &Nf));
508:   PetscCall(MatGetLocalSize(mass, &locRows, &locCols));
509:   PetscCall(PetscCalloc2(locRows, &dnz, locRows, &onz));
510:   PetscCall(PetscHSetIJCreate(&ht));

512:   PetscCall(PetscLayoutCreate(comm, &colLayout));
513:   PetscCall(PetscLayoutSetLocalSize(colLayout, locCols));
514:   PetscCall(PetscLayoutSetBlockSize(colLayout, 1));
515:   PetscCall(PetscLayoutSetUp(colLayout));
516:   PetscCall(PetscLayoutGetRange(colLayout, &colStart, &colEnd));
517:   PetscCall(PetscLayoutDestroy(&colLayout));

519:   PetscCall(PetscLayoutCreate(comm, &rLayout));
520:   PetscCall(PetscLayoutSetLocalSize(rLayout, locRows));
521:   PetscCall(PetscLayoutSetBlockSize(rLayout, 1));
522:   PetscCall(PetscLayoutSetUp(rLayout));
523:   PetscCall(PetscLayoutGetRange(rLayout, rStart, NULL));
524:   PetscCall(PetscLayoutDestroy(&rLayout));

526:   for (PetscInt field = 0; field < Nf; ++field) {
527:     PetscObject  obj;
528:     PetscClassId id;
529:     PetscInt     Nc;

531:     PetscCall(PetscDSGetDiscretization(ds, field, &obj));
532:     PetscCall(PetscObjectGetClassId(obj, &id));
533:     if (id == PETSCFE_CLASSID) PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
534:     else PetscCall(PetscFVGetNumComponents((PetscFV)obj, &Nc));
535:     totNc += Nc;
536:   }
537:   PetscCall(DMSwarmSortGetAccess(dmc));
538:   for (PetscInt field = 0; field < Nf; ++field) {
539:     PetscObject  obj;
540:     PetscClassId id;
541:     PetscInt     Nc;

543:     PetscCall(PetscDSGetDiscretization(ds, field, &obj));
544:     PetscCall(PetscObjectGetClassId(obj, &id));
545:     if (id == PETSCFE_CLASSID) PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
546:     else PetscCall(PetscFVGetNumComponents((PetscFV)obj, &Nc));

548:     for (PetscInt cell = cStart; cell < cEnd; ++cell) {
549:       PetscInt *findices, *cindices; /* fine is vertices, coarse is particles */
550:       PetscInt  numFIndices, numCIndices;

552:       PetscCall(DMPlexGetClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
553:       PetscCall(DMSwarmSortGetPointsPerCell(dmc, cell, &numCIndices, &cindices));
554:       *maxC = PetscMax(*maxC, numCIndices);
555:       {
556:         PetscHashIJKey key;
557:         PetscBool      missing;
558:         for (PetscInt i = 0; i < numFIndices; ++i) {
559:           key.j = findices[i]; /* global column (from Plex) */
560:           if (key.j >= 0) {
561:             /* Get indices for coarse elements */
562:             for (PetscInt j = 0; j < numCIndices; ++j) {
563:               for (PetscInt c = 0; c < Nc; ++c) {
564:                 // TODO Need field offset on particle here
565:                 key.i = cindices[j] * totNc + c + *rStart; /* global cols (from Swarm) */
566:                 if (key.i < 0) continue;
567:                 PetscCall(PetscHSetIJQueryAdd(ht, key, &missing));
568:                 PetscCheck(missing, PetscObjectComm((PetscObject)dmf), PETSC_ERR_SUP, "Set new value at %" PetscInt_FMT ",%" PetscInt_FMT, key.i, key.j);
569:                 if (key.j >= colStart && key.j < colEnd) ++dnz[key.i - *rStart];
570:                 else ++onz[key.i - *rStart];
571:               }
572:             }
573:           }
574:         }
575:         PetscCall(DMSwarmSortRestorePointsPerCell(dmc, cell, &numCIndices, &cindices));
576:       }
577:       PetscCall(DMPlexRestoreClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
578:     }
579:   }
580:   PetscCall(DMSwarmSortRestoreAccess(dmc));
581:   PetscCall(PetscHSetIJDestroy(&ht));
582:   PetscCall(MatXAIJSetPreallocation(mass, 1, dnz, onz, NULL, NULL));
583:   PetscCall(MatSetOption(mass, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
584:   PetscCall(PetscFree2(dnz, onz));
585:   PetscFunctionReturn(PETSC_SUCCESS);
586: }

588: /*@
589:   DMSwarmFillMassMatrix - Assemble the particle mass matrix between a `DMSWARM` and a `DMPLEX`

591:   Collective

593:   Input Parameters:
594: + dmc              - The `DMSWARM` object
595: . dmf              - The `DMPLEX` object
596: . mass             - The mass matrix to fill up
597: . rStart           - The starting row index for this process
598: . maxC             - The maximum number of columns per row
599: . useDeltaFunction - Flag to use a delta function for the particle shape function
600: . Nfc              - The number of swarm coordinate fields
601: . bs               - The block size for each swarm coordinate field
602: . coordVals        - The values for each particle for each swarm coordinate field
603: - ctx              - The user context

605:   Level: developer

607: .seealso: [](ch_unstructured), `DM`, `DMSWARM`, `DMPLEX`, `DMCreateMassMatrix()`, `DMSwarmPreallocateMassMatrix()`
608: @*/
609: PetscErrorCode DMSwarmFillMassMatrix(DM dmc, DM dmf, Mat mass, PetscInt rStart, PetscInt maxC, PetscBool useDeltaFunction, PetscInt Nfc, const PetscInt bs[], PetscReal *coordVals[], PetscCtx ctx)
610: {
611:   PetscDS      ds;
612:   PetscSection fsection, globalFSection;
613:   PetscInt     dim, cStart, cEnd, Nf, totDim, totNc = 0, *rowIDXs;
614:   PetscReal   *xi, *v0, *J, *invJ, detJ = 1.0, v0ref[3] = {-1.0, -1.0, -1.0};
615:   PetscScalar *elemMat;

617:   PetscFunctionBegin;
621:   PetscCall(DMGetCoordinateDim(dmf, &dim));
622:   PetscCall(DMPlexGetHeightStratum(dmf, 0, &cStart, &cEnd));
623:   PetscCall(DMGetLocalSection(dmf, &fsection));
624:   PetscCall(DMGetGlobalSection(dmf, &globalFSection));
625:   PetscCall(DMGetDS(dmf, &ds));
626:   PetscCall(PetscDSGetNumFields(ds, &Nf));
627:   PetscCall(PetscDSGetTotalDimension(ds, &totDim));
628:   for (PetscInt field = 0; field < Nf; ++field) {
629:     PetscObject  obj;
630:     PetscClassId id;
631:     PetscInt     Nc;

633:     PetscCall(PetscDSGetDiscretization(ds, field, &obj));
634:     PetscCall(PetscObjectGetClassId(obj, &id));
635:     if (id == PETSCFE_CLASSID) PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
636:     else PetscCall(PetscFVGetNumComponents((PetscFV)obj, &Nc));
637:     totNc += Nc;
638:   }

640:   PetscCall(PetscMalloc3(maxC * totNc * totDim, &elemMat, maxC * totNc, &rowIDXs, maxC * dim, &xi));
641:   PetscCall(PetscMalloc3(dim, &v0, dim * dim, &J, dim * dim, &invJ));
642:   PetscCall(DMSwarmSortGetAccess(dmc));
643:   for (PetscInt field = 0; field < Nf; ++field) {
644:     PetscTabulation Tcoarse;
645:     PetscObject     obj;
646:     PetscClassId    id;
647:     PetscInt        Nc;

649:     PetscCall(PetscDSGetDiscretization(ds, field, &obj));
650:     PetscCall(PetscObjectGetClassId(obj, &id));
651:     if (id == PETSCFE_CLASSID) PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
652:     else PetscCall(PetscFVGetNumComponents((PetscFV)obj, &Nc));

654:     for (PetscInt cell = cStart; cell < cEnd; ++cell) {
655:       PetscInt *findices, *cindices;
656:       PetscInt  numFIndices, numCIndices;

658:       /* TODO: Use DMField instead of assuming affine */
659:       PetscCall(DMPlexComputeCellGeometryFEM(dmf, cell, NULL, v0, J, invJ, &detJ));
660:       PetscCall(DMPlexGetClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
661:       PetscCall(DMSwarmSortGetPointsPerCell(dmc, cell, &numCIndices, &cindices));
662:       for (PetscInt j = 0; j < numCIndices; ++j) {
663:         PetscReal xr[8];
664:         PetscInt  off = 0;

666:         for (PetscInt i = 0; i < Nfc; ++i) {
667:           for (PetscInt b = 0; b < bs[i]; ++b, ++off) xr[off] = coordVals[i][cindices[j] * bs[i] + b];
668:         }
669:         PetscCheck(off == dim, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The total block size of coordinates is %" PetscInt_FMT " != %" PetscInt_FMT " the DM coordinate dimension", off, dim);
670:         CoordinatesRealToRef(dim, dim, v0ref, v0, invJ, xr, &xi[j * dim]);
671:       }
672:       if (id == PETSCFE_CLASSID) PetscCall(PetscFECreateTabulation((PetscFE)obj, 1, numCIndices, xi, 0, &Tcoarse));
673:       else PetscCall(PetscFVCreateTabulation((PetscFV)obj, 1, numCIndices, xi, 0, &Tcoarse));
674:       /* Get elemMat entries by multiplying by weight */
675:       PetscCall(PetscArrayzero(elemMat, numCIndices * Nc * totDim));
676:       for (PetscInt i = 0; i < numFIndices / Nc; ++i) {
677:         for (PetscInt j = 0; j < numCIndices; ++j) {
678:           for (PetscInt c = 0; c < Nc; ++c) {
679:             // TODO Need field offset on particle and field here
680:             /* B[(p*pdim + i)*Nc + c] is the value at point p for basis function i and component c */
681:             elemMat[(j * totNc + c) * numFIndices + i * Nc + c] += Tcoarse->T[0][(j * numFIndices + i * Nc + c) * Nc + c] * (useDeltaFunction ? 1.0 : detJ);
682:           }
683:         }
684:       }
685:       for (PetscInt j = 0; j < numCIndices; ++j)
686:         // TODO Need field offset on particle here
687:         for (PetscInt c = 0; c < Nc; ++c) rowIDXs[j * Nc + c] = cindices[j] * totNc + c + rStart;
688:       if (0) PetscCall(DMPrintCellMatrix(cell, "Mass Matrix", numCIndices * Nc, numFIndices, elemMat));
689:       PetscCall(MatSetValues(mass, numCIndices * Nc, rowIDXs, numFIndices, findices, elemMat, ADD_VALUES));
690:       PetscCall(DMSwarmSortRestorePointsPerCell(dmc, cell, &numCIndices, &cindices));
691:       PetscCall(DMPlexRestoreClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
692:       PetscCall(PetscTabulationDestroy(&Tcoarse));
693:     }
694:   }
695:   PetscCall(DMSwarmSortRestoreAccess(dmc));
696:   PetscCall(PetscFree3(elemMat, rowIDXs, xi));
697:   PetscCall(PetscFree3(v0, J, invJ));
698:   PetscFunctionReturn(PETSC_SUCCESS);
699: }

701: /* This creates a "mass matrix" between a finite element and particle space. If a finite element interpolant is given by

703:      \hat f = \sum_i f_i \phi_i

705:    and a particle function is given by

707:      f = \sum_i w_i \delta(x - x_i)

709:    then we want to require that

711:      M \hat f = M_p f

713:    where the particle mass matrix is given by

715:      (M_p)_{ij} = \int \phi_i \delta(x - x_j)

717:    The way Dave May does particles, they amount to quadratue weights rather than delta functions, so he has |J| is in
718:    his integral. We allow this with the boolean flag.
719: */
720: static PetscErrorCode DMSwarmComputeMassMatrix_Private(DM dmc, DM dmf, Mat mass, PetscBool useDeltaFunction, PetscCtx ctx)
721: {
722:   DMSwarmCellDM celldm;
723:   PetscInt      rStart, maxC = 0;
724:   PetscInt      Nfc;
725:   const char  **coordFields;
726:   PetscReal   **coordVals;
727:   PetscInt     *bs;

729:   PetscFunctionBegin;
730:   PetscCall(DMSwarmPreallocateMassMatrix(dmc, dmf, mass, &rStart, &maxC, ctx));

732:   PetscCall(DMSwarmGetCellDMActive(dmc, &celldm));
733:   PetscCall(DMSwarmCellDMGetCoordinateFields(celldm, &Nfc, &coordFields));
734:   PetscCall(PetscMalloc2(Nfc, &coordVals, Nfc, &bs));
735:   for (PetscInt i = 0; i < Nfc; ++i) PetscCall(DMSwarmGetField(dmc, coordFields[i], &bs[i], NULL, (void **)&coordVals[i]));
736:   PetscCall(DMSwarmFillMassMatrix(dmc, dmf, mass, rStart, maxC, useDeltaFunction, Nfc, bs, coordVals, ctx));
737:   for (PetscInt i = 0; i < Nfc; ++i) PetscCall(DMSwarmRestoreField(dmc, coordFields[i], &bs[i], NULL, (void **)&coordVals[i]));
738:   PetscCall(PetscFree2(coordVals, bs));

740:   PetscCall(MatAssemblyBegin(mass, MAT_FINAL_ASSEMBLY));
741:   PetscCall(MatAssemblyEnd(mass, MAT_FINAL_ASSEMBLY));
742:   PetscFunctionReturn(PETSC_SUCCESS);
743: }

745: /* Returns empty matrix for use with SNES FD */
746: static PetscErrorCode DMCreateMatrix_Swarm(DM sw, Mat *m)
747: {
748:   Vec      field;
749:   PetscInt size;

751:   PetscFunctionBegin;
752:   PetscCall(DMGetGlobalVector(sw, &field));
753:   PetscCall(VecGetLocalSize(field, &size));
754:   PetscCall(DMRestoreGlobalVector(sw, &field));
755:   PetscCall(MatCreate(PETSC_COMM_WORLD, m));
756:   PetscCall(MatSetFromOptions(*m));
757:   PetscCall(MatSetSizes(*m, PETSC_DECIDE, PETSC_DECIDE, size, size));
758:   PetscCall(MatSeqAIJSetPreallocation(*m, 1, NULL));
759:   PetscCall(MatZeroEntries(*m));
760:   PetscCall(MatAssemblyBegin(*m, MAT_FINAL_ASSEMBLY));
761:   PetscCall(MatAssemblyEnd(*m, MAT_FINAL_ASSEMBLY));
762:   PetscCall(MatShift(*m, 1.0));
763:   PetscCall(MatSetDM(*m, sw));
764:   PetscFunctionReturn(PETSC_SUCCESS);
765: }

767: /* FEM cols, Particle rows */
768: static PetscErrorCode DMCreateMassMatrix_Swarm(DM dmCoarse, DM dmFine, Mat *mass)
769: {
770:   DMSwarmCellDM celldm;
771:   PetscSection  gsf;
772:   PetscInt      m, n, Np, bs;
773:   void         *ctx;

775:   PetscFunctionBegin;
776:   PetscCall(DMSwarmGetCellDMActive(dmCoarse, &celldm));
777:   PetscCheck(celldm->Nf, PetscObjectComm((PetscObject)dmCoarse), PETSC_ERR_USER, "Active cell DM does not define any fields");
778:   PetscCall(DMGetGlobalSection(dmFine, &gsf));
779:   PetscCall(PetscSectionGetConstrainedStorageSize(gsf, &m));
780:   PetscCall(DMSwarmGetLocalSize(dmCoarse, &Np));
781:   PetscCall(DMSwarmCellDMGetBlockSize(celldm, dmCoarse, &bs));
782:   n = Np * bs;
783:   PetscCall(MatCreate(PetscObjectComm((PetscObject)dmCoarse), mass));
784:   PetscCall(MatSetSizes(*mass, n, m, PETSC_DETERMINE, PETSC_DETERMINE));
785:   PetscCall(MatSetType(*mass, dmCoarse->mattype));
786:   PetscCall(DMGetApplicationContext(dmFine, &ctx));

788:   PetscCall(DMSwarmComputeMassMatrix_Private(dmCoarse, dmFine, *mass, PETSC_TRUE, ctx));
789:   PetscCall(MatViewFromOptions(*mass, NULL, "-mass_mat_view"));
790:   PetscFunctionReturn(PETSC_SUCCESS);
791: }

793: static PetscErrorCode DMSwarmComputeMassMatrixSquare_Private(DM dmc, DM dmf, Mat mass, PetscBool useDeltaFunction, PetscCtx ctx)
794: {
795:   MPI_Comm      comm;
796:   DMSwarmCellDM celldm;
797:   PetscDS       prob;
798:   PetscSection  fsection, globalFSection;
799:   PetscHSetIJ   ht;
800:   PetscLayout   rLayout, colLayout;
801:   PetscInt     *dnz, *onz, *adj, depth, maxConeSize, maxSupportSize, maxAdjSize;
802:   PetscInt      locRows, locCols, rStart, colStart, colEnd, *rowIDXs;
803:   PetscReal    *xi, *v0, *J, *invJ, detJ = 1.0, v0ref[3] = {-1.0, -1.0, -1.0};
804:   PetscScalar  *elemMat, *elemMatSq;
805:   PetscInt      cdim, Nf, Nfc, cStart, cEnd, totDim, maxC = 0;
806:   const char  **coordFields;
807:   PetscReal   **coordVals;
808:   PetscInt     *bs;

810:   PetscFunctionBegin;
811:   PetscCall(PetscObjectGetComm((PetscObject)mass, &comm));
812:   PetscCall(DMGetCoordinateDim(dmf, &cdim));
813:   PetscCall(DMGetDS(dmf, &prob));
814:   PetscCall(PetscDSGetNumFields(prob, &Nf));
815:   PetscCall(PetscDSGetTotalDimension(prob, &totDim));
816:   PetscCall(PetscMalloc3(cdim, &v0, cdim * cdim, &J, cdim * cdim, &invJ));
817:   PetscCall(DMGetLocalSection(dmf, &fsection));
818:   PetscCall(DMGetGlobalSection(dmf, &globalFSection));
819:   PetscCall(DMPlexGetHeightStratum(dmf, 0, &cStart, &cEnd));
820:   PetscCall(MatGetLocalSize(mass, &locRows, &locCols));

822:   PetscCall(DMSwarmGetCellDMActive(dmc, &celldm));
823:   PetscCall(DMSwarmCellDMGetCoordinateFields(celldm, &Nfc, &coordFields));
824:   PetscCall(PetscMalloc2(Nfc, &coordVals, Nfc, &bs));

826:   PetscCall(PetscLayoutCreate(comm, &colLayout));
827:   PetscCall(PetscLayoutSetLocalSize(colLayout, locCols));
828:   PetscCall(PetscLayoutSetBlockSize(colLayout, 1));
829:   PetscCall(PetscLayoutSetUp(colLayout));
830:   PetscCall(PetscLayoutGetRange(colLayout, &colStart, &colEnd));
831:   PetscCall(PetscLayoutDestroy(&colLayout));

833:   PetscCall(PetscLayoutCreate(comm, &rLayout));
834:   PetscCall(PetscLayoutSetLocalSize(rLayout, locRows));
835:   PetscCall(PetscLayoutSetBlockSize(rLayout, 1));
836:   PetscCall(PetscLayoutSetUp(rLayout));
837:   PetscCall(PetscLayoutGetRange(rLayout, &rStart, NULL));
838:   PetscCall(PetscLayoutDestroy(&rLayout));

840:   PetscCall(DMPlexGetDepth(dmf, &depth));
841:   PetscCall(DMPlexGetMaxSizes(dmf, &maxConeSize, &maxSupportSize));
842:   maxAdjSize = PetscPowInt(maxConeSize * maxSupportSize, depth);
843:   PetscCall(PetscMalloc1(maxAdjSize, &adj));

845:   PetscCall(PetscCalloc2(locRows, &dnz, locRows, &onz));
846:   PetscCall(PetscHSetIJCreate(&ht));
847:   /* Count nonzeros
848:        This is just FVM++, but we cannot use the Plex P0 allocation since unknowns in a cell will not be contiguous
849:   */
850:   PetscCall(DMSwarmSortGetAccess(dmc));
851:   for (PetscInt cell = cStart; cell < cEnd; ++cell) {
852:     PetscInt *cindices;
853:     PetscInt  numCIndices;
854: #if 0
855:     PetscInt  adjSize = maxAdjSize, a, j;
856: #endif

858:     PetscCall(DMSwarmSortGetPointsPerCell(dmc, cell, &numCIndices, &cindices));
859:     maxC = PetscMax(maxC, numCIndices);
860:     /* Diagonal block */
861:     for (PetscInt i = 0; i < numCIndices; ++i) dnz[cindices[i]] += numCIndices;
862: #if 0
863:     /* Off-diagonal blocks */
864:     PetscCall(DMPlexGetAdjacency(dmf, cell, &adjSize, &adj));
865:     for (a = 0; a < adjSize; ++a) {
866:       if (adj[a] >= cStart && adj[a] < cEnd && adj[a] != cell) {
867:         const PetscInt ncell = adj[a];
868:         PetscInt      *ncindices;
869:         PetscInt       numNCIndices;

871:         PetscCall(DMSwarmSortGetPointsPerCell(dmc, ncell, &numNCIndices, &ncindices));
872:         {
873:           PetscHashIJKey key;
874:           PetscBool      missing;

876:           for (i = 0; i < numCIndices; ++i) {
877:             key.i = cindices[i] + rStart; /* global rows (from Swarm) */
878:             if (key.i < 0) continue;
879:             for (j = 0; j < numNCIndices; ++j) {
880:               key.j = ncindices[j] + rStart; /* global column (from Swarm) */
881:               if (key.j < 0) continue;
882:               PetscCall(PetscHSetIJQueryAdd(ht, key, &missing));
883:               if (missing) {
884:                 if (key.j >= colStart && key.j < colEnd) ++dnz[key.i - rStart];
885:                 else ++onz[key.i - rStart];
886:               }
887:             }
888:           }
889:         }
890:         PetscCall(DMSwarmSortRestorePointsPerCell(dmc, ncell, &numNCIndices, &ncindices));
891:       }
892:     }
893: #endif
894:     PetscCall(DMSwarmSortRestorePointsPerCell(dmc, cell, &numCIndices, &cindices));
895:   }
896:   PetscCall(PetscHSetIJDestroy(&ht));
897:   PetscCall(MatXAIJSetPreallocation(mass, 1, dnz, onz, NULL, NULL));
898:   PetscCall(MatSetOption(mass, MAT_NEW_NONZERO_ALLOCATION_ERR, PETSC_TRUE));
899:   PetscCall(PetscFree2(dnz, onz));
900:   PetscCall(PetscMalloc4(maxC * totDim, &elemMat, maxC * maxC, &elemMatSq, maxC, &rowIDXs, maxC * cdim, &xi));
901:   /* Fill in values
902:        Each entry is a sum of terms \phi_i(x_p) \phi_i(x_q)
903:        Start just by producing block diagonal
904:        Could loop over adjacent cells
905:          Produce neighboring element matrix
906:          TODO Determine which columns and rows correspond to shared dual vector
907:          Do MatMatMult with rectangular matrices
908:          Insert block
909:   */
910:   for (PetscInt field = 0; field < Nf; ++field) {
911:     PetscTabulation Tcoarse;
912:     PetscObject     obj;
913:     PetscInt        Nc;

915:     PetscCall(PetscDSGetDiscretization(prob, field, &obj));
916:     PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
917:     PetscCheck(Nc == 1, PetscObjectComm((PetscObject)dmf), PETSC_ERR_SUP, "Can only interpolate a scalar field from particles, Nc = %" PetscInt_FMT, Nc);
918:     for (PetscInt i = 0; i < Nfc; ++i) PetscCall(DMSwarmGetField(dmc, coordFields[i], &bs[i], NULL, (void **)&coordVals[i]));
919:     for (PetscInt cell = cStart; cell < cEnd; ++cell) {
920:       PetscInt *findices, *cindices;
921:       PetscInt  numFIndices, numCIndices;

923:       /* TODO: Use DMField instead of assuming affine */
924:       PetscCall(DMPlexComputeCellGeometryFEM(dmf, cell, NULL, v0, J, invJ, &detJ));
925:       PetscCall(DMPlexGetClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
926:       PetscCall(DMSwarmSortGetPointsPerCell(dmc, cell, &numCIndices, &cindices));
927:       for (PetscInt p = 0; p < numCIndices; ++p) {
928:         PetscReal xr[8];
929:         PetscInt  off = 0;

931:         for (PetscInt i = 0; i < Nfc; ++i) {
932:           for (PetscInt b = 0; b < bs[i]; ++b, ++off) xr[off] = coordVals[i][cindices[p] * bs[i] + b];
933:         }
934:         PetscCheck(off == cdim, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The total block size of coordinates is %" PetscInt_FMT " != %" PetscInt_FMT " the DM coordinate dimension", off, cdim);
935:         CoordinatesRealToRef(cdim, cdim, v0ref, v0, invJ, xr, &xi[p * cdim]);
936:       }
937:       PetscCall(PetscFECreateTabulation((PetscFE)obj, 1, numCIndices, xi, 0, &Tcoarse));
938:       /* Get elemMat entries by multiplying by weight */
939:       PetscCall(PetscArrayzero(elemMat, numCIndices * totDim));
940:       for (PetscInt i = 0; i < numFIndices; ++i) {
941:         for (PetscInt p = 0; p < numCIndices; ++p) {
942:           for (PetscInt c = 0; c < Nc; ++c) {
943:             /* B[(p*pdim + i)*Nc + c] is the value at point p for basis function i and component c */
944:             elemMat[p * numFIndices + i] += Tcoarse->T[0][(p * numFIndices + i) * Nc + c] * (useDeltaFunction ? 1.0 : detJ);
945:           }
946:         }
947:       }
948:       PetscCall(PetscTabulationDestroy(&Tcoarse));
949:       for (PetscInt p = 0; p < numCIndices; ++p) rowIDXs[p] = cindices[p] + rStart;
950:       if (0) PetscCall(DMPrintCellMatrix(cell, "Mass Matrix Square", 1, numCIndices, elemMat));
951:       /* Block diagonal */
952:       if (numCIndices) {
953:         PetscBLASInt blasn, blask;
954:         PetscScalar  one = 1.0, zero = 0.0;

956:         PetscCall(PetscBLASIntCast(numCIndices, &blasn));
957:         PetscCall(PetscBLASIntCast(numFIndices, &blask));
958:         PetscCallBLAS("BLASgemm", BLASgemm_("T", "N", &blasn, &blasn, &blask, &one, elemMat, &blask, elemMat, &blask, &zero, elemMatSq, &blasn));
959:       }
960:       PetscCall(MatSetValues(mass, numCIndices, rowIDXs, numCIndices, rowIDXs, elemMatSq, ADD_VALUES));
961:       /* TODO off-diagonal */
962:       PetscCall(DMSwarmSortRestorePointsPerCell(dmc, cell, &numCIndices, &cindices));
963:       PetscCall(DMPlexRestoreClosureIndices(dmf, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
964:     }
965:     for (PetscInt i = 0; i < Nfc; ++i) PetscCall(DMSwarmRestoreField(dmc, coordFields[i], &bs[i], NULL, (void **)&coordVals[i]));
966:   }
967:   PetscCall(PetscFree4(elemMat, elemMatSq, rowIDXs, xi));
968:   PetscCall(PetscFree(adj));
969:   PetscCall(DMSwarmSortRestoreAccess(dmc));
970:   PetscCall(PetscFree3(v0, J, invJ));
971:   PetscCall(PetscFree2(coordVals, bs));
972:   PetscCall(MatAssemblyBegin(mass, MAT_FINAL_ASSEMBLY));
973:   PetscCall(MatAssemblyEnd(mass, MAT_FINAL_ASSEMBLY));
974:   PetscFunctionReturn(PETSC_SUCCESS);
975: }

977: /*@
978:   DMSwarmCreateMassMatrixSquare - Creates the block-diagonal of the square, M^T_p M_p, of the particle mass matrix M_p

980:   Collective

982:   Input Parameters:
983: + dmCoarse - a `DMSWARM`
984: - dmFine   - a `DMPLEX`

986:   Output Parameter:
987: . mass - the square of the particle mass matrix

989:   Level: advanced

991:   Note:
992:   We only compute the block diagonal since this provides a good preconditioner and is completely local. It would be possible in the
993:   future to compute the full normal equations.

995: .seealso: `DM`, `DMSWARM`, `DMCreateMassMatrix()`
996: @*/
997: PetscErrorCode DMSwarmCreateMassMatrixSquare(DM dmCoarse, DM dmFine, Mat *mass)
998: {
999:   PetscInt n;
1000:   void    *ctx;

1002:   PetscFunctionBegin;
1003:   PetscCall(DMSwarmGetLocalSize(dmCoarse, &n));
1004:   PetscCall(MatCreate(PetscObjectComm((PetscObject)dmCoarse), mass));
1005:   PetscCall(MatSetSizes(*mass, n, n, PETSC_DETERMINE, PETSC_DETERMINE));
1006:   PetscCall(MatSetType(*mass, dmCoarse->mattype));
1007:   PetscCall(DMGetApplicationContext(dmFine, &ctx));

1009:   PetscCall(DMSwarmComputeMassMatrixSquare_Private(dmCoarse, dmFine, *mass, PETSC_TRUE, ctx));
1010:   PetscCall(MatViewFromOptions(*mass, NULL, "-mass_sq_mat_view"));
1011:   PetscFunctionReturn(PETSC_SUCCESS);
1012: }

1014: /* This creates a "gradient matrix" between a finite element and particle space, which is meant to enforce a weak divergence condition on the particle space. We are looking for a finite element field that has the same divergence as our particle field, so that

1016:      \int_X \psi_i \nabla \cdot \hat f = \int_X \psi_i \nabla \cdot f

1018:    and then integrate by parts

1020:      \int_X \nabla \psi_i \cdot \hat f = \int_X \nabla \psi_i \cdot f

1022:    where \psi is from a scalar FE space. If a finite element interpolant is given by

1024:      \hat f^c = \sum_i f_i \phi^c_i

1026:    and a particle function is given by

1028:      f^c = \sum_p f^c_p \delta(x - x_p)

1030:    then we want to require that

1032:      D_f \hat f = D_p f

1034:    where the gradient matrices are given by

1036:      (D_f)_{i(jc)} = \int \partial_c \psi_i \phi_j
1037:      (D_p)_{i(jc)} = \int \partial_c \psi_i \delta(x - x_j)

1039:    Thus we need two finite element spaces, a scalar and a vector. The vector space holds the representer for the
1040:    vector particle field. The scalar space holds the output of D_p or D_f, which is the weak divergence of the field.

1042:    The way Dave May does particles, they amount to quadratue weights rather than delta functions, so he has |J| is in
1043:    his integral. We allow this with the boolean flag.
1044: */
1045: static PetscErrorCode DMSwarmComputeGradientMatrix_Private(DM sw, DM dm, Mat derv, PetscBool useDeltaFunction, PetscCtx ctx)
1046: {
1047:   MPI_Comm      comm;
1048:   DMSwarmCellDM celldm;
1049:   PetscDS       ds;
1050:   PetscSection  fsection, globalFSection;
1051:   PetscLayout   rLayout;
1052:   PetscInt      locRows, rStart, *rowIDXs;
1053:   PetscReal    *xi, *v0, *J, *invJ, detJ = 1.0, v0ref[3] = {-1.0, -1.0, -1.0};
1054:   PetscScalar  *elemMat;
1055:   PetscInt      cdim, Nf, Nfc, cStart, cEnd, totDim, maxNpc = 0, totNc = 0;
1056:   const char  **coordFields;
1057:   PetscReal   **coordVals;
1058:   PetscInt     *bs;

1060:   PetscFunctionBegin;
1061:   PetscCall(PetscObjectGetComm((PetscObject)derv, &comm));
1062:   PetscCall(DMGetCoordinateDim(dm, &cdim));
1063:   PetscCall(DMGetDS(dm, &ds));
1064:   PetscCall(PetscDSGetNumFields(ds, &Nf));
1065:   PetscCheck(Nf == 1, comm, PETSC_ERR_SUP, "Currently, we only support a single field");
1066:   PetscCall(PetscDSGetTotalDimension(ds, &totDim));
1067:   PetscCall(PetscMalloc3(cdim, &v0, cdim * cdim, &J, cdim * cdim, &invJ));
1068:   PetscCall(DMGetLocalSection(dm, &fsection));
1069:   PetscCall(DMGetGlobalSection(dm, &globalFSection));
1070:   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
1071:   PetscCall(MatGetLocalSize(derv, &locRows, NULL));

1073:   PetscCall(DMSwarmGetCellDMActive(sw, &celldm));
1074:   PetscCall(DMSwarmCellDMGetCoordinateFields(celldm, &Nfc, &coordFields));
1075:   PetscCheck(Nfc == 1, comm, PETSC_ERR_SUP, "Currently, we only support a single field");
1076:   PetscCall(PetscMalloc2(Nfc, &coordVals, Nfc, &bs));

1078:   PetscCall(PetscLayoutCreate(comm, &rLayout));
1079:   PetscCall(PetscLayoutSetLocalSize(rLayout, locRows));
1080:   PetscCall(PetscLayoutSetBlockSize(rLayout, cdim));
1081:   PetscCall(PetscLayoutSetUp(rLayout));
1082:   PetscCall(PetscLayoutGetRange(rLayout, &rStart, NULL));
1083:   PetscCall(PetscLayoutDestroy(&rLayout));

1085:   for (PetscInt field = 0; field < Nf; ++field) {
1086:     PetscObject obj;
1087:     PetscInt    Nc;

1089:     PetscCall(PetscDSGetDiscretization(ds, field, &obj));
1090:     PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
1091:     totNc += Nc;
1092:   }
1093:   PetscCheck(totNc == 1, comm, PETSC_ERR_ARG_WRONG, "The number of field components %" PetscInt_FMT " != 1", totNc);
1094:   /* count non-zeros */
1095:   PetscCall(DMSwarmSortGetAccess(sw));
1096:   for (PetscInt field = 0; field < Nf; ++field) {
1097:     PetscObject obj;
1098:     PetscInt    Nc;

1100:     PetscCall(PetscDSGetDiscretization(ds, field, &obj));
1101:     PetscCall(PetscFEGetNumComponents((PetscFE)obj, &Nc));
1102:     for (PetscInt cell = cStart; cell < cEnd; ++cell) {
1103:       PetscInt *pind;
1104:       PetscInt  Npc;

1106:       PetscCall(DMSwarmSortGetPointsPerCell(sw, cell, &Npc, &pind));
1107:       maxNpc = PetscMax(maxNpc, Npc);
1108:       PetscCall(DMSwarmSortRestorePointsPerCell(sw, cell, &Npc, &pind));
1109:     }
1110:   }
1111:   PetscCall(PetscMalloc3(maxNpc * cdim * totDim, &elemMat, maxNpc * cdim, &rowIDXs, maxNpc * cdim, &xi));
1112:   for (PetscInt field = 0; field < Nf; ++field) {
1113:     PetscTabulation Tcoarse;
1114:     PetscFE         fe;

1116:     PetscCall(PetscDSGetDiscretization(ds, field, (PetscObject *)&fe));
1117:     for (PetscInt i = 0; i < Nfc; ++i) PetscCall(DMSwarmGetField(sw, coordFields[i], &bs[i], NULL, (void **)&coordVals[i]));
1118:     for (PetscInt cell = cStart; cell < cEnd; ++cell) {
1119:       PetscInt *findices, *pind;
1120:       PetscInt  numFIndices, Npc;

1122:       /* TODO: Use DMField instead of assuming affine */
1123:       PetscCall(DMPlexComputeCellGeometryFEM(dm, cell, NULL, v0, J, invJ, &detJ));
1124:       PetscCall(DMPlexGetClosureIndices(dm, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
1125:       PetscCall(DMSwarmSortGetPointsPerCell(sw, cell, &Npc, &pind));
1126:       for (PetscInt j = 0; j < Npc; ++j) {
1127:         PetscReal xr[8];
1128:         PetscInt  off = 0;

1130:         for (PetscInt i = 0; i < Nfc; ++i) {
1131:           for (PetscInt b = 0; b < bs[i]; ++b, ++off) xr[off] = coordVals[i][pind[j] * bs[i] + b];
1132:         }
1133:         PetscCheck(off == cdim, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "The total block size of coordinates is %" PetscInt_FMT " != %" PetscInt_FMT " the DM coordinate dimension", off, cdim);
1134:         CoordinatesRealToRef(cdim, cdim, v0ref, v0, invJ, xr, &xi[j * cdim]);
1135:       }
1136:       PetscCall(PetscFECreateTabulation(fe, 1, Npc, xi, 1, &Tcoarse));
1137:       /* Get elemMat entries by multiplying by weight */
1138:       PetscCall(PetscArrayzero(elemMat, Npc * cdim * totDim));
1139:       for (PetscInt i = 0; i < numFIndices; ++i) {
1140:         for (PetscInt j = 0; j < Npc; ++j) {
1141:           /* D[((p*pdim + i)*Nc + c)*cdim + d] is the value at point p for basis function i, component c, derivative d */
1142:           for (PetscInt d = 0; d < cdim; ++d) {
1143:             xi[d] = 0.;
1144:             for (PetscInt e = 0; e < cdim; ++e) xi[d] += invJ[e * cdim + d] * Tcoarse->T[1][(j * numFIndices + i) * cdim + e];
1145:             elemMat[(j * cdim + d) * numFIndices + i] += xi[d] * (useDeltaFunction ? 1.0 : detJ);
1146:           }
1147:         }
1148:       }
1149:       for (PetscInt j = 0; j < Npc; ++j)
1150:         for (PetscInt d = 0; d < cdim; ++d) rowIDXs[j * cdim + d] = pind[j] * cdim + d + rStart;
1151:       if (0) PetscCall(DMPrintCellMatrix(cell, "Derivative Matrix", Npc * cdim, numFIndices, elemMat));
1152:       PetscCall(MatSetValues(derv, Npc * cdim, rowIDXs, numFIndices, findices, elemMat, ADD_VALUES));
1153:       PetscCall(DMSwarmSortRestorePointsPerCell(sw, cell, &Npc, &pind));
1154:       PetscCall(DMPlexRestoreClosureIndices(dm, fsection, globalFSection, cell, PETSC_FALSE, &numFIndices, &findices, NULL, NULL));
1155:       PetscCall(PetscTabulationDestroy(&Tcoarse));
1156:     }
1157:     for (PetscInt i = 0; i < Nfc; ++i) PetscCall(DMSwarmRestoreField(sw, coordFields[i], &bs[i], NULL, (void **)&coordVals[i]));
1158:   }
1159:   PetscCall(PetscFree3(elemMat, rowIDXs, xi));
1160:   PetscCall(DMSwarmSortRestoreAccess(sw));
1161:   PetscCall(PetscFree3(v0, J, invJ));
1162:   PetscCall(PetscFree2(coordVals, bs));
1163:   PetscCall(MatAssemblyBegin(derv, MAT_FINAL_ASSEMBLY));
1164:   PetscCall(MatAssemblyEnd(derv, MAT_FINAL_ASSEMBLY));
1165:   PetscFunctionReturn(PETSC_SUCCESS);
1166: }

1168: /* FEM cols:      this is a scalar space
1169:    Particle rows: this is a vector space that contracts with the derivative
1170: */
1171: static PetscErrorCode DMCreateGradientMatrix_Swarm(DM sw, DM dm, Mat *derv)
1172: {
1173:   DMSwarmCellDM celldm;
1174:   PetscSection  gs;
1175:   PetscInt      cdim, m, n, Np, bs;
1176:   void         *ctx;
1177:   MPI_Comm      comm;

1179:   PetscFunctionBegin;
1180:   PetscCall(PetscObjectGetComm((PetscObject)sw, &comm));
1181:   PetscCall(DMGetCoordinateDim(dm, &cdim));
1182:   PetscCall(DMSwarmGetCellDMActive(sw, &celldm));
1183:   PetscCheck(celldm->Nf, comm, PETSC_ERR_USER, "Active cell DM does not define any fields");
1184:   PetscCall(DMGetGlobalSection(dm, &gs));
1185:   PetscCall(PetscSectionGetConstrainedStorageSize(gs, &n));
1186:   PetscCall(DMSwarmGetLocalSize(sw, &Np));
1187:   PetscCall(DMSwarmCellDMGetBlockSize(celldm, sw, &bs));
1188:   PetscCheck(cdim == bs, comm, PETSC_ERR_ARG_WRONG, "Coordinate dimension %" PetscInt_FMT " != %" PetscInt_FMT " swarm field block size", cdim, bs);
1189:   m = Np * bs;
1190:   PetscCall(MatCreate(PetscObjectComm((PetscObject)sw), derv));
1191:   PetscCall(PetscObjectSetName((PetscObject)*derv, "Swarm Derivative Matrix"));
1192:   PetscCall(MatSetSizes(*derv, m, n, PETSC_DETERMINE, PETSC_DETERMINE));
1193:   PetscCall(MatSetType(*derv, sw->mattype));
1194:   PetscCall(DMGetApplicationContext(dm, &ctx));

1196:   PetscCall(DMSwarmComputeGradientMatrix_Private(sw, dm, *derv, PETSC_TRUE, ctx));
1197:   PetscCall(MatViewFromOptions(*derv, NULL, "-gradient_mat_view"));
1198:   PetscFunctionReturn(PETSC_SUCCESS);
1199: }

1201: /*@
1202:   DMSwarmCreateGlobalVectorFromField - Creates a `Vec` object sharing the array associated with a given field

1204:   Collective

1206:   Input Parameters:
1207: + dm        - a `DMSWARM`
1208: - fieldname - the textual name given to a registered field

1210:   Output Parameter:
1211: . vec - the vector

1213:   Level: beginner

1215:   Note:
1216:   The vector must be returned using a matching call to `DMSwarmDestroyGlobalVectorFromField()`.

1218:   The field must have data type `PETSC_SCALAR`.

1220: .seealso: `DM`, `DMSWARM`, `DMSwarmRegisterPetscDatatypeField()`, `DMSwarmDestroyGlobalVectorFromField()`
1221: @*/
1222: PetscErrorCode DMSwarmCreateGlobalVectorFromField(DM dm, const char fieldname[], Vec *vec)
1223: {
1224:   MPI_Comm comm = PetscObjectComm((PetscObject)dm);

1226:   PetscFunctionBegin;
1228:   PetscCall(DMSwarmCreateVectorFromField_Private(dm, fieldname, comm, vec));
1229:   PetscFunctionReturn(PETSC_SUCCESS);
1230: }

1232: /*@
1233:   DMSwarmDestroyGlobalVectorFromField - Destroys the `Vec` object which share the array associated with a given field

1235:   Collective

1237:   Input Parameters:
1238: + dm        - a `DMSWARM`
1239: - fieldname - the textual name given to a registered field

1241:   Output Parameter:
1242: . vec - the vector

1244:   Level: beginner

1246: .seealso: `DM`, `DMSWARM`, `DMSwarmRegisterPetscDatatypeField()`, `DMSwarmCreateGlobalVectorFromField()`
1247: @*/
1248: PetscErrorCode DMSwarmDestroyGlobalVectorFromField(DM dm, const char fieldname[], Vec *vec)
1249: {
1250:   PetscFunctionBegin;
1252:   PetscCall(DMSwarmDestroyVectorFromField_Private(dm, fieldname, vec));
1253:   PetscFunctionReturn(PETSC_SUCCESS);
1254: }

1256: /*@
1257:   DMSwarmCreateLocalVectorFromField - Creates a `Vec` object sharing the array associated with a given field

1259:   Collective

1261:   Input Parameters:
1262: + dm        - a `DMSWARM`
1263: - fieldname - the textual name given to a registered field

1265:   Output Parameter:
1266: . vec - the vector

1268:   Level: beginner

1270:   Note:
1271:   The vector must be returned using a matching call to DMSwarmDestroyLocalVectorFromField().

1273:   The field must have data type `PETSC_SCALAR`.

1275: .seealso: `DM`, `DMSWARM`, `DMSwarmRegisterPetscDatatypeField()`, `DMSwarmDestroyLocalVectorFromField()`
1276: @*/
1277: PetscErrorCode DMSwarmCreateLocalVectorFromField(DM dm, const char fieldname[], Vec *vec)
1278: {
1279:   PetscFunctionBegin;
1280:   PetscCall(DMSwarmCreateVectorFromField_Private(dm, fieldname, PETSC_COMM_SELF, vec));
1281:   PetscFunctionReturn(PETSC_SUCCESS);
1282: }

1284: /*@
1285:   DMSwarmDestroyLocalVectorFromField - Destroys the `Vec` object which share the array associated with a given field

1287:   Collective

1289:   Input Parameters:
1290: + dm        - a `DMSWARM`
1291: - fieldname - the textual name given to a registered field

1293:   Output Parameter:
1294: . vec - the vector

1296:   Level: beginner

1298: .seealso: `DM`, `DMSWARM`, `DMSwarmRegisterPetscDatatypeField()`, `DMSwarmCreateLocalVectorFromField()`
1299: @*/
1300: PetscErrorCode DMSwarmDestroyLocalVectorFromField(DM dm, const char fieldname[], Vec *vec)
1301: {
1302:   PetscFunctionBegin;
1304:   PetscCall(DMSwarmDestroyVectorFromField_Private(dm, fieldname, vec));
1305:   PetscFunctionReturn(PETSC_SUCCESS);
1306: }

1308: /*@
1309:   DMSwarmCreateGlobalVectorFromFields - Creates a `Vec` object sharing the array associated with a given field set

1311:   Collective

1313:   Input Parameters:
1314: + dm         - a `DMSWARM`
1315: . Nf         - the number of fields
1316: - fieldnames - the textual names given to the registered fields

1318:   Output Parameter:
1319: . vec - the vector

1321:   Level: beginner

1323:   Notes:
1324:   The vector must be returned using a matching call to `DMSwarmDestroyGlobalVectorFromFields()`.

1326:   All fields must have data type `PETSC_REAL` or `PETSC_SCALAR`. When PETSc is configured with complex scalars,
1327:   only the real part of vector entries is copied back to `PETSC_REAL` fields.

1329:   This vector is copyin-copyout, rather than a direct pointer like `DMSwarmCreateGlobalVectorFromField()`

1331: .seealso: `DM`, `DMSWARM`, `DMSwarmRegisterPetscDatatypeField()`, `DMSwarmDestroyGlobalVectorFromFields()`
1332: @*/
1333: PetscErrorCode DMSwarmCreateGlobalVectorFromFields(DM dm, PetscInt Nf, const char *fieldnames[], Vec *vec)
1334: {
1335:   MPI_Comm comm = PetscObjectComm((PetscObject)dm);

1337:   PetscFunctionBegin;
1339:   PetscCall(DMSwarmCreateVectorFromFields_Private(dm, Nf, fieldnames, comm, vec));
1340:   PetscFunctionReturn(PETSC_SUCCESS);
1341: }

1343: /*@
1344:   DMSwarmDestroyGlobalVectorFromFields - Destroys the `Vec` object which share the array associated with a given field set

1346:   Collective

1348:   Input Parameters:
1349: + dm         - a `DMSWARM`
1350: . Nf         - the number of fields
1351: - fieldnames - the textual names given to the registered fields

1353:   Output Parameter:
1354: . vec - the vector

1356:   Level: beginner

1358: .seealso: `DM`, `DMSWARM`, `DMSwarmRegisterPetscDatatypeField()`, `DMSwarmCreateGlobalVectorFromField()`
1359: @*/
1360: PetscErrorCode DMSwarmDestroyGlobalVectorFromFields(DM dm, PetscInt Nf, const char *fieldnames[], Vec *vec)
1361: {
1362:   PetscFunctionBegin;
1364:   PetscCall(DMSwarmDestroyVectorFromFields_Private(dm, Nf, fieldnames, vec));
1365:   PetscFunctionReturn(PETSC_SUCCESS);
1366: }

1368: /*@
1369:   DMSwarmCreateLocalVectorFromFields - Creates a `Vec` object sharing the array associated with a given field set

1371:   Collective

1373:   Input Parameters:
1374: + dm         - a `DMSWARM`
1375: . Nf         - the number of fields
1376: - fieldnames - the textual names given to the registered fields

1378:   Output Parameter:
1379: . vec - the vector

1381:   Level: beginner

1383:   Notes:
1384:   The vector must be returned using a matching call to DMSwarmDestroyLocalVectorFromField().

1386:   All fields must have data type `PETSC_REAL` or `PETSC_SCALAR`. When PETSc is configured with complex scalars,
1387:   only the real part of vector entries is copied back to `PETSC_REAL` fields.

1389:   This vector is copyin-copyout, rather than a direct pointer like `DMSwarmCreateLocalVectorFromField()`

1391: .seealso: `DM`, `DMSWARM`, `DMSwarmRegisterPetscDatatypeField()`, `DMSwarmDestroyLocalVectorFromField()`
1392: @*/
1393: PetscErrorCode DMSwarmCreateLocalVectorFromFields(DM dm, PetscInt Nf, const char *fieldnames[], Vec *vec)
1394: {
1395:   PetscFunctionBegin;
1396:   PetscCall(DMSwarmCreateVectorFromFields_Private(dm, Nf, fieldnames, PETSC_COMM_SELF, vec));
1397:   PetscFunctionReturn(PETSC_SUCCESS);
1398: }

1400: /*@
1401:   DMSwarmDestroyLocalVectorFromFields - Destroys the `Vec` object which share the array associated with a given field set

1403:   Collective

1405:   Input Parameters:
1406: + dm         - a `DMSWARM`
1407: . Nf         - the number of fields
1408: - fieldnames - the textual names given to the registered fields

1410:   Output Parameter:
1411: . vec - the vector

1413:   Level: beginner

1415: .seealso: `DM`, `DMSWARM`, `DMSwarmRegisterPetscDatatypeField()`, `DMSwarmCreateLocalVectorFromFields()`
1416: @*/
1417: PetscErrorCode DMSwarmDestroyLocalVectorFromFields(DM dm, PetscInt Nf, const char *fieldnames[], Vec *vec)
1418: {
1419:   PetscFunctionBegin;
1421:   PetscCall(DMSwarmDestroyVectorFromFields_Private(dm, Nf, fieldnames, vec));
1422:   PetscFunctionReturn(PETSC_SUCCESS);
1423: }

1425: /*@
1426:   DMSwarmInitializeFieldRegister - Initiates the registration of fields to a `DMSWARM`

1428:   Collective

1430:   Input Parameter:
1431: . dm - a `DMSWARM`

1433:   Level: beginner

1435:   Note:
1436:   After all fields have been registered, you must call `DMSwarmFinalizeFieldRegister()`.

1438: .seealso: `DM`, `DMSWARM`, `DMSwarmFinalizeFieldRegister()`, `DMSwarmRegisterPetscDatatypeField()`,
1439:           `DMSwarmRegisterUserStructField()`, `DMSwarmRegisterUserDatatypeField()`
1440: @*/
1441: PetscErrorCode DMSwarmInitializeFieldRegister(DM dm)
1442: {
1443:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

1445:   PetscFunctionBegin;
1446:   if (!swarm->field_registration_initialized) {
1447:     swarm->field_registration_initialized = PETSC_TRUE;
1448:     PetscCall(DMSwarmRegisterPetscDatatypeField(dm, DMSwarmField_pid, 1, PETSC_INT64)); /* unique identifier */
1449:     PetscCall(DMSwarmRegisterPetscDatatypeField(dm, DMSwarmField_rank, 1, PETSC_INT));  /* used for communication */
1450:   }
1451:   PetscFunctionReturn(PETSC_SUCCESS);
1452: }

1454: /*@
1455:   DMSwarmFinalizeFieldRegister - Finalizes the registration of fields to a `DMSWARM`

1457:   Collective

1459:   Input Parameter:
1460: . dm - a `DMSWARM`

1462:   Level: beginner

1464:   Note:
1465:   After `DMSwarmFinalizeFieldRegister()` has been called, no new fields can be defined on the `DMSWARM`.

1467: .seealso: `DM`, `DMSWARM`, `DMSwarmInitializeFieldRegister()`, `DMSwarmRegisterPetscDatatypeField()`,
1468:           `DMSwarmRegisterUserStructField()`, `DMSwarmRegisterUserDatatypeField()`
1469: @*/
1470: PetscErrorCode DMSwarmFinalizeFieldRegister(DM dm)
1471: {
1472:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

1474:   PetscFunctionBegin;
1475:   if (!swarm->field_registration_finalized) PetscCall(DMSwarmDataBucketFinalize(swarm->db));
1476:   swarm->field_registration_finalized = PETSC_TRUE;
1477:   PetscFunctionReturn(PETSC_SUCCESS);
1478: }

1480: /*@
1481:   DMSwarmSetLocalSizes - Sets the length of all registered fields on the `DMSWARM`

1483:   Not Collective

1485:   Input Parameters:
1486: + sw     - a `DMSWARM`
1487: . nlocal - the length of each registered field
1488: - buffer - the length of the buffer used to efficient dynamic re-sizing

1490:   Level: beginner

1492: .seealso: `DM`, `DMSWARM`, `DMSwarmGetLocalSize()`
1493: @*/
1494: PetscErrorCode DMSwarmSetLocalSizes(DM sw, PetscInt nlocal, PetscInt buffer)
1495: {
1496:   DM_Swarm   *swarm = (DM_Swarm *)sw->data;
1497:   PetscMPIInt rank;
1498:   PetscInt   *rankval;

1500:   PetscFunctionBegin;
1501:   PetscCall(PetscLogEventBegin(DMSWARM_SetSizes, 0, 0, 0, 0));
1502:   PetscCall(DMSwarmDataBucketSetSizes(swarm->db, nlocal, buffer));
1503:   PetscCall(PetscLogEventEnd(DMSWARM_SetSizes, 0, 0, 0, 0));

1505:   // Initialize values in pid and rank placeholders
1506:   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)sw), &rank));
1507:   PetscCall(DMSwarmGetField(sw, DMSwarmField_rank, NULL, NULL, (void **)&rankval));
1508:   for (PetscInt p = 0; p < nlocal; p++) rankval[p] = rank;
1509:   PetscCall(DMSwarmRestoreField(sw, DMSwarmField_rank, NULL, NULL, (void **)&rankval));
1510:   /* TODO: [pid - use MPI_Scan] */
1511:   PetscFunctionReturn(PETSC_SUCCESS);
1512: }

1514: /*@
1515:   DMSwarmSetCellDM - Attaches a `DM` to a `DMSWARM`

1517:   Collective

1519:   Input Parameters:
1520: + sw - a `DMSWARM`
1521: - dm - the `DM` to attach to the `DMSWARM`

1523:   Level: beginner

1525:   Note:
1526:   The attached `DM` (dm) will be queried for point location and
1527:   neighbor MPI-rank information if `DMSwarmMigrate()` is called.

1529: .seealso: `DM`, `DMSWARM`, `DMSwarmSetType()`, `DMSwarmGetCellDM()`, `DMSwarmMigrate()`
1530: @*/
1531: PetscErrorCode DMSwarmSetCellDM(DM sw, DM dm)
1532: {
1533:   DMSwarmCellDM celldm;
1534:   const char   *name;
1535:   char         *coordName;

1537:   PetscFunctionBegin;
1540:   PetscCall(PetscStrallocpy(DMSwarmPICField_coor, &coordName));
1541:   PetscCall(DMSwarmCellDMCreate(dm, 0, NULL, 1, (const char **)&coordName, &celldm));
1542:   PetscCall(PetscFree(coordName));
1543:   PetscCall(PetscObjectGetName((PetscObject)celldm, &name));
1544:   PetscCall(DMSwarmAddCellDM(sw, celldm));
1545:   PetscCall(DMSwarmCellDMDestroy(&celldm));
1546:   PetscCall(DMSwarmSetCellDMActive(sw, name));
1547:   PetscFunctionReturn(PETSC_SUCCESS);
1548: }

1550: /*@
1551:   DMSwarmGetCellDM - Fetches the active cell `DM`

1553:   Collective

1555:   Input Parameter:
1556: . sw - a `DMSWARM`

1558:   Output Parameter:
1559: . dm - the active `DM` for the `DMSWARM`

1561:   Level: beginner

1563: .seealso: `DM`, `DMSWARM`, `DMSwarmSetCellDM()`
1564: @*/
1565: PetscErrorCode DMSwarmGetCellDM(DM sw, DM *dm)
1566: {
1567:   DM_Swarm     *swarm = (DM_Swarm *)sw->data;
1568:   DMSwarmCellDM celldm;

1570:   PetscFunctionBegin;
1572:   PetscCall(PetscObjectListFind(swarm->cellDMs, swarm->activeCellDM, (PetscObject *)&celldm));
1573:   PetscCheck(celldm, PetscObjectComm((PetscObject)sw), PETSC_ERR_ARG_WRONG, "There is no cell DM named %s in this Swarm", swarm->activeCellDM);
1574:   PetscCall(DMSwarmCellDMGetDM(celldm, dm));
1575:   PetscFunctionReturn(PETSC_SUCCESS);
1576: }

1578: /*@
1579:   DMSwarmGetCellDMNames - Get the list of cell `DM` names

1581:   Not collective

1583:   Input Parameter:
1584: . sw - a `DMSWARM`

1586:   Output Parameters:
1587: + Ndm     - the number of `DMSwarmCellDM` in the `DMSWARM`
1588: - celldms - the name of each `DMSwarmCellDM`

1590:   Level: beginner

1592: .seealso: `DM`, `DMSWARM`, `DMSwarmSetCellDM()`, `DMSwarmGetCellDMByName()`
1593: @*/
1594: PetscErrorCode DMSwarmGetCellDMNames(DM sw, PetscInt *Ndm, const char **celldms[])
1595: {
1596:   DM_Swarm       *swarm = (DM_Swarm *)sw->data;
1597:   PetscObjectList next  = swarm->cellDMs;
1598:   PetscInt        n     = 0;

1600:   PetscFunctionBegin;
1602:   PetscAssertPointer(Ndm, 2);
1603:   PetscAssertPointer(celldms, 3);
1604:   while (next) {
1605:     next = next->next;
1606:     ++n;
1607:   }
1608:   PetscCall(PetscMalloc1(n, celldms));
1609:   next = swarm->cellDMs;
1610:   n    = 0;
1611:   while (next) {
1612:     (*celldms)[n] = (const char *)next->obj->name;
1613:     next          = next->next;
1614:     ++n;
1615:   }
1616:   *Ndm = n;
1617:   PetscFunctionReturn(PETSC_SUCCESS);
1618: }

1620: /*@
1621:   DMSwarmSetCellDMActive - Activates a cell `DM` for a `DMSWARM`

1623:   Collective

1625:   Input Parameters:
1626: + sw   - a `DMSWARM`
1627: - name - name of the cell `DM` to active for the `DMSWARM`

1629:   Level: beginner

1631:   Note:
1632:   The attached `DM` (dmcell) will be queried for point location and
1633:   neighbor MPI-rank information if `DMSwarmMigrate()` is called.

1635: .seealso: `DM`, `DMSWARM`, `DMSwarmCellDM`, `DMSwarmSetType()`, `DMSwarmAddCellDM()`, `DMSwarmSetCellDM()`, `DMSwarmMigrate()`
1636: @*/
1637: PetscErrorCode DMSwarmSetCellDMActive(DM sw, const char name[])
1638: {
1639:   DM_Swarm     *swarm = (DM_Swarm *)sw->data;
1640:   DMSwarmCellDM celldm;

1642:   PetscFunctionBegin;
1644:   PetscCall(PetscInfo(sw, "Setting cell DM to %s\n", name));
1645:   PetscCall(PetscFree(swarm->activeCellDM));
1646:   PetscCall(PetscStrallocpy(name, (char **)&swarm->activeCellDM));
1647:   PetscCall(DMSwarmGetCellDMActive(sw, &celldm));
1648:   PetscFunctionReturn(PETSC_SUCCESS);
1649: }

1651: /*@
1652:   DMSwarmGetCellDMActive - Returns the active cell `DM` for a `DMSWARM`

1654:   Collective

1656:   Input Parameter:
1657: . sw - a `DMSWARM`

1659:   Output Parameter:
1660: . celldm - the active `DMSwarmCellDM`

1662:   Level: beginner

1664: .seealso: `DM`, `DMSWARM`, `DMSwarmCellDM`, `DMSwarmSetType()`, `DMSwarmAddCellDM()`, `DMSwarmSetCellDM()`, `DMSwarmMigrate()`
1665: @*/
1666: PetscErrorCode DMSwarmGetCellDMActive(DM sw, DMSwarmCellDM *celldm)
1667: {
1668:   DM_Swarm *swarm = (DM_Swarm *)sw->data;

1670:   PetscFunctionBegin;
1672:   PetscAssertPointer(celldm, 2);
1673:   PetscCheck(swarm->activeCellDM, PetscObjectComm((PetscObject)sw), PETSC_ERR_ARG_WRONGSTATE, "Swarm has no active cell DM");
1674:   PetscCall(PetscObjectListFind(swarm->cellDMs, swarm->activeCellDM, (PetscObject *)celldm));
1675:   PetscCheck(*celldm, PetscObjectComm((PetscObject)sw), PETSC_ERR_ARG_WRONGSTATE, "Swarm has no valid cell DM for %s", swarm->activeCellDM);
1676:   PetscFunctionReturn(PETSC_SUCCESS);
1677: }

1679: /*@
1680:   DMSwarmGetCellDMByName - Get a `DMSwarmCellDM` from its name

1682:   Not collective

1684:   Input Parameters:
1685: + sw   - a `DMSWARM`
1686: - name - the name

1688:   Output Parameter:
1689: . celldm - the `DMSwarmCellDM`, or `NULL` if the name is unknown

1691:   Level: beginner

1693: .seealso: `DM`, `DMSWARM`, `DMSwarmSetCellDM()`, `DMSwarmGetCellDMNames()`
1694: @*/
1695: PetscErrorCode DMSwarmGetCellDMByName(DM sw, const char name[], DMSwarmCellDM *celldm)
1696: {
1697:   DM_Swarm *swarm = (DM_Swarm *)sw->data;

1699:   PetscFunctionBegin;
1701:   PetscAssertPointer(name, 2);
1702:   PetscAssertPointer(celldm, 3);
1703:   PetscCall(PetscObjectListFind(swarm->cellDMs, name, (PetscObject *)celldm));
1704:   PetscFunctionReturn(PETSC_SUCCESS);
1705: }

1707: /*@
1708:   DMSwarmAddCellDM - Adds a cell `DM` to the `DMSWARM`

1710:   Collective

1712:   Input Parameters:
1713: + sw     - a `DMSWARM`
1714: - celldm - the `DMSwarmCellDM`

1716:   Level: beginner

1718:   Note:
1719:   Cell DMs with the same name will share the cellid field

1721: .seealso: `DM`, `DMSWARM`, `DMSwarmSetType()`, `DMSwarmPushCellDM()`, `DMSwarmSetCellDM()`, `DMSwarmMigrate()`
1722: @*/
1723: PetscErrorCode DMSwarmAddCellDM(DM sw, DMSwarmCellDM celldm)
1724: {
1725:   DM_Swarm   *swarm = (DM_Swarm *)sw->data;
1726:   const char *name;
1727:   PetscInt    dim;
1728:   PetscBool   flg;
1729:   MPI_Comm    comm;

1731:   PetscFunctionBegin;
1733:   PetscCall(PetscObjectGetComm((PetscObject)sw, &comm));
1735:   PetscCall(PetscObjectGetName((PetscObject)celldm, &name));
1736:   PetscCall(PetscObjectListAdd(&swarm->cellDMs, name, (PetscObject)celldm));
1737:   PetscCall(DMGetDimension(sw, &dim));
1738:   for (PetscInt f = 0; f < celldm->Nfc; ++f) {
1739:     PetscCall(DMSwarmDataFieldStringInList(celldm->coordFields[f], swarm->db->nfields, (const DMSwarmDataField *)swarm->db->field, &flg));
1740:     if (!flg) {
1741:       PetscCall(DMSwarmRegisterPetscDatatypeField(sw, celldm->coordFields[f], dim, PETSC_REAL));
1742:     } else {
1743:       PetscDataType dt;
1744:       PetscInt      bs;

1746:       PetscCall(DMSwarmGetFieldInfo(sw, celldm->coordFields[f], &bs, &dt));
1747:       PetscCheck(bs == dim, comm, PETSC_ERR_ARG_WRONG, "Coordinate field %s has blocksize %" PetscInt_FMT " != %" PetscInt_FMT " spatial dimension", celldm->coordFields[f], bs, dim);
1748:       PetscCheck(dt == PETSC_REAL, comm, PETSC_ERR_ARG_WRONG, "Coordinate field %s has datatype %s != PETSC_REAL", celldm->coordFields[f], PetscDataTypes[dt]);
1749:     }
1750:   }
1751:   // Assume that DMs with the same name share the cellid field
1752:   PetscCall(DMSwarmDataFieldStringInList(celldm->cellid, swarm->db->nfields, (const DMSwarmDataField *)swarm->db->field, &flg));
1753:   if (!flg) {
1754:     PetscBool   isShell, isDummy;
1755:     const char *name;

1757:     // Allow dummy DMSHELL (I don't think we should support this mode)
1758:     PetscCall(PetscObjectTypeCompare((PetscObject)celldm->dm, DMSHELL, &isShell));
1759:     PetscCall(PetscObjectGetName((PetscObject)celldm->dm, &name));
1760:     PetscCall(PetscStrcmp(name, "dummy", &isDummy));
1761:     if (!isShell || !isDummy) PetscCall(DMSwarmRegisterPetscDatatypeField(sw, celldm->cellid, 1, PETSC_INT));
1762:   }
1763:   PetscCall(DMSwarmSetCellDMActive(sw, name));
1764:   PetscFunctionReturn(PETSC_SUCCESS);
1765: }

1767: /*@
1768:   DMSwarmGetLocalSize - Retrieves the local length of fields registered

1770:   Not Collective

1772:   Input Parameter:
1773: . dm - a `DMSWARM`

1775:   Output Parameter:
1776: . nlocal - the length of each registered field

1778:   Level: beginner

1780: .seealso: `DM`, `DMSWARM`, `DMSwarmGetSize()`, `DMSwarmSetLocalSizes()`
1781: @*/
1782: PetscErrorCode DMSwarmGetLocalSize(DM dm, PetscInt *nlocal)
1783: {
1784:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

1786:   PetscFunctionBegin;
1787:   PetscCall(DMSwarmDataBucketGetSizes(swarm->db, nlocal, NULL, NULL));
1788:   PetscFunctionReturn(PETSC_SUCCESS);
1789: }

1791: /*@
1792:   DMSwarmGetSize - Retrieves the total length of fields registered

1794:   Collective

1796:   Input Parameter:
1797: . dm - a `DMSWARM`

1799:   Output Parameter:
1800: . n - the total length of each registered field

1802:   Level: beginner

1804:   Note:
1805:   This calls `MPI_Allreduce()` upon each call (inefficient but safe)

1807: .seealso: `DM`, `DMSWARM`, `DMSwarmGetLocalSize()`, `DMSwarmSetLocalSizes()`
1808: @*/
1809: PetscErrorCode DMSwarmGetSize(DM dm, PetscInt *n)
1810: {
1811:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

1813:   PetscFunctionBegin;
1814:   PetscCall(DMSwarmDataBucketGetSizes(swarm->db, n, NULL, NULL));
1815:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, n, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)dm)));
1816:   PetscFunctionReturn(PETSC_SUCCESS);
1817: }

1819: /*@
1820:   DMSwarmRegisterPetscDatatypeField - Register a field to a `DMSWARM` with a native PETSc data type

1822:   Collective

1824:   Input Parameters:
1825: + dm        - a `DMSWARM`
1826: . fieldname - the textual name to identify this field
1827: . blocksize - the number of each data type
1828: - type      - a valid PETSc data type (`PETSC_CHAR`, `PETSC_SHORT`, `PETSC_INT`, `PETSC_FLOAT`, `PETSC_REAL`, `PETSC_LONG`)

1830:   Level: beginner

1832:   Notes:
1833:   The textual name for each registered field must be unique.

1835: .seealso: `DM`, `DMSWARM`, `DMSwarmRegisterUserStructField()`, `DMSwarmRegisterUserDatatypeField()`
1836: @*/
1837: PetscErrorCode DMSwarmRegisterPetscDatatypeField(DM dm, const char fieldname[], PetscInt blocksize, PetscDataType type)
1838: {
1839:   DM_Swarm *swarm = (DM_Swarm *)dm->data;
1840:   size_t    size;

1842:   PetscFunctionBegin;
1843:   PetscCheck(swarm->field_registration_initialized, PetscObjectComm((PetscObject)dm), PETSC_ERR_USER, "Must call DMSwarmInitializeFieldRegister() first");
1844:   PetscCheck(!swarm->field_registration_finalized, PetscObjectComm((PetscObject)dm), PETSC_ERR_USER, "Cannot register additional fields after calling DMSwarmFinalizeFieldRegister() first");

1846:   PetscCheck(type != PETSC_OBJECT, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Valid for {char,short,int,long,float,double}");
1847:   PetscCheck(type != PETSC_FUNCTION, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Valid for {char,short,int,long,float,double}");
1848:   PetscCheck(type != PETSC_STRING, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Valid for {char,short,int,long,float,double}");
1849:   PetscCheck(type != PETSC_STRUCT, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Valid for {char,short,int,long,float,double}");
1850:   PetscCheck(type != PETSC_DATATYPE_UNKNOWN, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "Valid for {char,short,int,long,float,double}");

1852:   PetscCall(PetscDataTypeGetSize(type, &size));
1853:   /* Load a specific data type into data bucket, specifying textual name and its size in bytes */
1854:   PetscCall(DMSwarmDataBucketRegisterField(swarm->db, "DMSwarmRegisterPetscDatatypeField", fieldname, blocksize * size, NULL));
1855:   {
1856:     DMSwarmDataField gfield;

1858:     PetscCall(DMSwarmDataBucketGetDMSwarmDataFieldByName(swarm->db, fieldname, &gfield));
1859:     PetscCall(DMSwarmDataFieldSetBlockSize(gfield, blocksize));
1860:   }
1861:   swarm->db->field[swarm->db->nfields - 1]->petsc_type = type;
1862:   PetscFunctionReturn(PETSC_SUCCESS);
1863: }

1865: /*@
1866:   DMSwarmRegisterUserStructField - Register a user defined struct to a `DMSWARM`

1868:   Collective

1870:   Input Parameters:
1871: + dm        - a `DMSWARM`
1872: . fieldname - the textual name to identify this field
1873: - size      - the size in bytes of the user struct of each data type

1875:   Level: beginner

1877:   Note:
1878:   The textual name for each registered field must be unique.

1880: .seealso: `DM`, `DMSWARM`, `DMSwarmRegisterPetscDatatypeField()`, `DMSwarmRegisterUserDatatypeField()`
1881: @*/
1882: PetscErrorCode DMSwarmRegisterUserStructField(DM dm, const char fieldname[], size_t size)
1883: {
1884:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

1886:   PetscFunctionBegin;
1887:   PetscCall(DMSwarmDataBucketRegisterField(swarm->db, "DMSwarmRegisterUserStructField", fieldname, size, NULL));
1888:   swarm->db->field[swarm->db->nfields - 1]->petsc_type = PETSC_STRUCT;
1889:   PetscFunctionReturn(PETSC_SUCCESS);
1890: }

1892: /*@
1893:   DMSwarmRegisterUserDatatypeField - Register a user defined data type to a `DMSWARM`

1895:   Collective

1897:   Input Parameters:
1898: + dm        - a `DMSWARM`
1899: . fieldname - the textual name to identify this field
1900: . size      - the size in bytes of the user data type
1901: - blocksize - the number of each data type

1903:   Level: beginner

1905:   Note:
1906:   The textual name for each registered field must be unique.

1908: .seealso: `DM`, `DMSWARM`, `DMSwarmRegisterPetscDatatypeField()`, `DMSwarmRegisterUserStructField()`
1909: @*/
1910: PetscErrorCode DMSwarmRegisterUserDatatypeField(DM dm, const char fieldname[], size_t size, PetscInt blocksize)
1911: {
1912:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

1914:   PetscFunctionBegin;
1915:   PetscCall(DMSwarmDataBucketRegisterField(swarm->db, "DMSwarmRegisterUserDatatypeField", fieldname, blocksize * size, NULL));
1916:   {
1917:     DMSwarmDataField gfield;

1919:     PetscCall(DMSwarmDataBucketGetDMSwarmDataFieldByName(swarm->db, fieldname, &gfield));
1920:     PetscCall(DMSwarmDataFieldSetBlockSize(gfield, blocksize));
1921:   }
1922:   swarm->db->field[swarm->db->nfields - 1]->petsc_type = PETSC_DATATYPE_UNKNOWN;
1923:   PetscFunctionReturn(PETSC_SUCCESS);
1924: }

1926: /*@
1927:   DMSwarmGetField - Get access to the underlying array storing all entries associated with a registered field

1929:   Not Collective, No Fortran Support

1931:   Input Parameters:
1932: + dm        - a `DMSWARM`
1933: - fieldname - the textual name to identify this field

1935:   Output Parameters:
1936: + blocksize - the number of each data type
1937: . type      - the data type
1938: - data      - pointer to raw array

1940:   Level: beginner

1942:   Notes:
1943:   The array must be returned using a matching call to `DMSwarmRestoreField()`.

1945:   Fortran Note:
1946:   Only works for `type` of `PETSC_SCALAR`

1948: .seealso: `DM`, `DMSWARM`, `DMSwarmRestoreField()`
1949: @*/
1950: PetscErrorCode DMSwarmGetField(DM dm, const char fieldname[], PetscInt *blocksize, PetscDataType *type, void **data) PeNS
1951: {
1952:   DM_Swarm        *swarm = (DM_Swarm *)dm->data;
1953:   DMSwarmDataField gfield;

1955:   PetscFunctionBegin;
1957:   if (!swarm->issetup) PetscCall(DMSetUp(dm));
1958:   PetscCall(DMSwarmDataBucketGetDMSwarmDataFieldByName(swarm->db, fieldname, &gfield));
1959:   PetscCall(DMSwarmDataFieldGetAccess(gfield));
1960:   PetscCall(DMSwarmDataFieldGetEntries(gfield, data));
1961:   if (blocksize) *blocksize = gfield->bs;
1962:   if (type) *type = gfield->petsc_type;
1963:   PetscFunctionReturn(PETSC_SUCCESS);
1964: }

1966: /*@
1967:   DMSwarmRestoreField - Restore access to the underlying array storing all entries associated with a registered field

1969:   Not Collective

1971:   Input Parameters:
1972: + dm        - a `DMSWARM`
1973: - fieldname - the textual name to identify this field

1975:   Output Parameters:
1976: + blocksize - the number of each data type
1977: . type      - the data type
1978: - data      - pointer to raw array

1980:   Level: beginner

1982:   Notes:
1983:   The user must call `DMSwarmGetField()` prior to calling `DMSwarmRestoreField()`.

1985:   Fortran Note:
1986:   Only works for `type` of `PETSC_SCALAR`

1988: .seealso: `DM`, `DMSWARM`, `DMSwarmGetField()`
1989: @*/
1990: PetscErrorCode DMSwarmRestoreField(DM dm, const char fieldname[], PetscInt *blocksize, PetscDataType *type, void **data) PeNS
1991: {
1992:   DM_Swarm        *swarm = (DM_Swarm *)dm->data;
1993:   DMSwarmDataField gfield;

1995:   PetscFunctionBegin;
1997:   PetscCall(DMSwarmDataBucketGetDMSwarmDataFieldByName(swarm->db, fieldname, &gfield));
1998:   PetscCall(DMSwarmDataFieldRestoreAccess(gfield));
1999:   if (data) *data = NULL;
2000:   PetscFunctionReturn(PETSC_SUCCESS);
2001: }

2003: /*@
2004:   DMSwarmGetFieldInfo - Return the block size and data type of a registered `DMSWARM` field without accessing its data.

2006:   Not Collective

2008:   Input Parameters:
2009: + dm        - a `DMSWARM`
2010: - fieldname - the name of the registered field

2012:   Output Parameters:
2013: + blocksize - the number of entries of `type` per particle, or `NULL`
2014: - type      - the `PetscDataType` of a single entry, or `NULL`

2016:   Level: intermediate

2018: .seealso: `DM`, `DMSWARM`, `DMSwarmGetField()`, `DMSwarmRestoreField()`, `DMSwarmRegisterPetscDatatypeField()`
2019: @*/
2020: PetscErrorCode DMSwarmGetFieldInfo(DM dm, const char fieldname[], PetscInt *blocksize, PetscDataType *type)
2021: {
2022:   DM_Swarm        *swarm = (DM_Swarm *)dm->data;
2023:   DMSwarmDataField gfield;

2025:   PetscFunctionBegin;
2027:   PetscCall(DMSwarmDataBucketGetDMSwarmDataFieldByName(swarm->db, fieldname, &gfield));
2028:   if (blocksize) *blocksize = gfield->bs;
2029:   if (type) *type = gfield->petsc_type;
2030:   PetscFunctionReturn(PETSC_SUCCESS);
2031: }

2033: /*@
2034:   DMSwarmAddPoint - Add space for one new point in the `DMSWARM`

2036:   Not Collective

2038:   Input Parameter:
2039: . dm - a `DMSWARM`

2041:   Level: beginner

2043:   Notes:
2044:   The new point will have all fields initialized to zero.

2046: .seealso: `DM`, `DMSWARM`, `DMSwarmAddNPoints()`
2047: @*/
2048: PetscErrorCode DMSwarmAddPoint(DM dm)
2049: {
2050:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

2052:   PetscFunctionBegin;
2053:   if (!swarm->issetup) PetscCall(DMSetUp(dm));
2054:   PetscCall(PetscLogEventBegin(DMSWARM_AddPoints, 0, 0, 0, 0));
2055:   PetscCall(DMSwarmDataBucketAddPoint(swarm->db));
2056:   PetscCall(PetscLogEventEnd(DMSWARM_AddPoints, 0, 0, 0, 0));
2057:   PetscFunctionReturn(PETSC_SUCCESS);
2058: }

2060: /*@
2061:   DMSwarmAddNPoints - Add space for a number of new points in the `DMSWARM`

2063:   Not Collective

2065:   Input Parameters:
2066: + dm      - a `DMSWARM`
2067: - npoints - the number of new points to add

2069:   Level: beginner

2071:   Notes:
2072:   The new point will have all fields initialized to zero.

2074: .seealso: `DM`, `DMSWARM`, `DMSwarmAddPoint()`
2075: @*/
2076: PetscErrorCode DMSwarmAddNPoints(DM dm, PetscInt npoints)
2077: {
2078:   DM_Swarm *swarm = (DM_Swarm *)dm->data;
2079:   PetscInt  nlocal;

2081:   PetscFunctionBegin;
2082:   PetscCall(PetscLogEventBegin(DMSWARM_AddPoints, 0, 0, 0, 0));
2083:   PetscCall(DMSwarmDataBucketGetSizes(swarm->db, &nlocal, NULL, NULL));
2084:   nlocal = PetscMax(nlocal, 0) + npoints;
2085:   PetscCall(DMSwarmDataBucketSetSizes(swarm->db, nlocal, DMSWARM_DATA_BUCKET_BUFFER_DEFAULT));
2086:   PetscCall(PetscLogEventEnd(DMSWARM_AddPoints, 0, 0, 0, 0));
2087:   PetscFunctionReturn(PETSC_SUCCESS);
2088: }

2090: /*@
2091:   DMSwarmRemovePoint - Remove the last point from the `DMSWARM`

2093:   Not Collective

2095:   Input Parameter:
2096: . dm - a `DMSWARM`

2098:   Level: beginner

2100: .seealso: `DM`, `DMSWARM`, `DMSwarmRemovePointAtIndex()`
2101: @*/
2102: PetscErrorCode DMSwarmRemovePoint(DM dm)
2103: {
2104:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

2106:   PetscFunctionBegin;
2107:   PetscCall(PetscLogEventBegin(DMSWARM_RemovePoints, 0, 0, 0, 0));
2108:   PetscCall(DMSwarmDataBucketRemovePoint(swarm->db));
2109:   PetscCall(PetscLogEventEnd(DMSWARM_RemovePoints, 0, 0, 0, 0));
2110:   PetscFunctionReturn(PETSC_SUCCESS);
2111: }

2113: /*@
2114:   DMSwarmRemovePointAtIndex - Removes a specific point from the `DMSWARM`

2116:   Not Collective

2118:   Input Parameters:
2119: + dm  - a `DMSWARM`
2120: - idx - index of point to remove

2122:   Level: beginner

2124: .seealso: `DM`, `DMSWARM`, `DMSwarmRemovePoint()`
2125: @*/
2126: PetscErrorCode DMSwarmRemovePointAtIndex(DM dm, PetscInt idx)
2127: {
2128:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

2130:   PetscFunctionBegin;
2131:   PetscCall(PetscLogEventBegin(DMSWARM_RemovePoints, 0, 0, 0, 0));
2132:   PetscCall(DMSwarmDataBucketRemovePointAtIndex(swarm->db, idx));
2133:   PetscCall(PetscLogEventEnd(DMSWARM_RemovePoints, 0, 0, 0, 0));
2134:   PetscFunctionReturn(PETSC_SUCCESS);
2135: }

2137: /*@
2138:   DMSwarmCopyPoint - Copy point pj to point pi in the `DMSWARM`

2140:   Not Collective

2142:   Input Parameters:
2143: + dm - a `DMSWARM`
2144: . pi - the index of the point to copy
2145: - pj - the point index where the copy should be located

2147:   Level: beginner

2149: .seealso: `DM`, `DMSWARM`, `DMSwarmRemovePoint()`
2150: @*/
2151: PetscErrorCode DMSwarmCopyPoint(DM dm, PetscInt pi, PetscInt pj)
2152: {
2153:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

2155:   PetscFunctionBegin;
2156:   if (!swarm->issetup) PetscCall(DMSetUp(dm));
2157:   PetscCall(DMSwarmDataBucketCopyPoint(swarm->db, pi, swarm->db, pj));
2158:   PetscFunctionReturn(PETSC_SUCCESS);
2159: }

2161: static PetscErrorCode DMSwarmMigrate_Basic(DM dm, PetscBool remove_sent_points)
2162: {
2163:   PetscFunctionBegin;
2164:   PetscCall(DMSwarmMigrate_Push_Basic(dm, remove_sent_points));
2165:   PetscFunctionReturn(PETSC_SUCCESS);
2166: }

2168: /*@
2169:   DMSwarmMigrate - Relocates points defined in the `DMSWARM` to other MPI-ranks

2171:   Collective

2173:   Input Parameters:
2174: + dm                 - the `DMSWARM`
2175: - remove_sent_points - flag indicating if sent points should be removed from the current MPI-rank

2177:   Level: advanced

2179:   Notes:
2180:   The `DM` will be modified to accommodate received points.
2181:   If `remove_sent_points` is `PETSC_TRUE`, any points that were sent will be removed from the `DM`.
2182:   Different styles of migration are supported. See `DMSwarmSetMigrateType()`.

2184: .seealso: `DM`, `DMSWARM`, `DMSwarmSetMigrateType()`
2185: @*/
2186: PetscErrorCode DMSwarmMigrate(DM dm, PetscBool remove_sent_points)
2187: {
2188:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

2190:   PetscFunctionBegin;
2191:   PetscCall(PetscLogEventBegin(DMSWARM_Migrate, 0, 0, 0, 0));
2192:   switch (swarm->migrate_type) {
2193:   case DMSWARM_MIGRATE_BASIC:
2194:     PetscCall(DMSwarmMigrate_Basic(dm, remove_sent_points));
2195:     break;
2196:   case DMSWARM_MIGRATE_DMCELLNSCATTER:
2197:     PetscCall(DMSwarmMigrate_CellDMScatter(dm, remove_sent_points));
2198:     break;
2199:   case DMSWARM_MIGRATE_DMCELLEXACT:
2200:     SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, "DMSWARM_MIGRATE_DMCELLEXACT not implemented");
2201:   case DMSWARM_MIGRATE_USER:
2202:     SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, "DMSWARM_MIGRATE_USER not implemented");
2203:   default:
2204:     SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, "DMSWARM_MIGRATE type unknown");
2205:   }
2206:   PetscCall(PetscLogEventEnd(DMSWARM_Migrate, 0, 0, 0, 0));
2207:   PetscCall(DMClearGlobalVectors(dm));
2208:   PetscFunctionReturn(PETSC_SUCCESS);
2209: }

2211: PetscErrorCode DMSwarmMigrate_GlobalToLocal_Basic(DM dm, PetscInt *globalsize);

2213: /*
2214:  DMSwarmCollectViewCreate

2216:  * Applies a collection method and gathers point neighbour points into dm

2218:  Notes:
2219:  Users should call DMSwarmCollectViewDestroy() after
2220:  they have finished computations associated with the collected points
2221: */

2223: /*@
2224:   DMSwarmCollectViewCreate - Applies a collection method and gathers points
2225:   in neighbour ranks into the `DMSWARM`

2227:   Collective

2229:   Input Parameter:
2230: . dm - the `DMSWARM`

2232:   Level: advanced

2234:   Notes:
2235:   Users should call `DMSwarmCollectViewDestroy()` after
2236:   they have finished computations associated with the collected points

2238:   Different collect methods are supported. See `DMSwarmSetCollectType()`.

2240:   Developer Note:
2241:   Create and Destroy routines create new objects that can get destroyed, they do not change the state
2242:   of the current object.

2244: .seealso: `DM`, `DMSWARM`, `DMSwarmCollectViewDestroy()`, `DMSwarmSetCollectType()`
2245: @*/
2246: PetscErrorCode DMSwarmCollectViewCreate(DM dm)
2247: {
2248:   DM_Swarm *swarm = (DM_Swarm *)dm->data;
2249:   PetscInt  ng;

2251:   PetscFunctionBegin;
2252:   PetscCheck(!swarm->collect_view_active, PetscObjectComm((PetscObject)dm), PETSC_ERR_USER, "CollectView currently active");
2253:   PetscCall(DMSwarmGetLocalSize(dm, &ng));
2254:   switch (swarm->collect_type) {
2255:   case DMSWARM_COLLECT_BASIC:
2256:     PetscCall(DMSwarmMigrate_GlobalToLocal_Basic(dm, &ng));
2257:     break;
2258:   case DMSWARM_COLLECT_DMDABOUNDINGBOX:
2259:     SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, "DMSWARM_COLLECT_DMDABOUNDINGBOX not implemented");
2260:   case DMSWARM_COLLECT_GENERAL:
2261:     SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, "DMSWARM_COLLECT_GENERAL not implemented");
2262:   default:
2263:     SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, "DMSWARM_COLLECT type unknown");
2264:   }
2265:   swarm->collect_view_active       = PETSC_TRUE;
2266:   swarm->collect_view_reset_nlocal = ng;
2267:   PetscFunctionReturn(PETSC_SUCCESS);
2268: }

2270: /*@
2271:   DMSwarmCollectViewDestroy - Resets the `DMSWARM` to the size prior to calling `DMSwarmCollectViewCreate()`

2273:   Collective

2275:   Input Parameters:
2276: . dm - the `DMSWARM`

2278:   Notes:
2279:   Users should call `DMSwarmCollectViewCreate()` before this function is called.

2281:   Level: advanced

2283:   Developer Note:
2284:   Create and Destroy routines create new objects that can get destroyed, they do not change the state
2285:   of the current object.

2287: .seealso: `DM`, `DMSWARM`, `DMSwarmCollectViewCreate()`, `DMSwarmSetCollectType()`
2288: @*/
2289: PetscErrorCode DMSwarmCollectViewDestroy(DM dm)
2290: {
2291:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

2293:   PetscFunctionBegin;
2294:   PetscCheck(swarm->collect_view_active, PetscObjectComm((PetscObject)dm), PETSC_ERR_USER, "CollectView is currently not active");
2295:   PetscCall(DMSwarmSetLocalSizes(dm, swarm->collect_view_reset_nlocal, -1));
2296:   swarm->collect_view_active = PETSC_FALSE;
2297:   PetscFunctionReturn(PETSC_SUCCESS);
2298: }

2300: static PetscErrorCode DMSwarmSetUpPIC(DM dm)
2301: {
2302:   PetscInt dim;

2304:   PetscFunctionBegin;
2305:   PetscCall(DMSwarmSetNumSpecies(dm, 1));
2306:   PetscCall(DMGetDimension(dm, &dim));
2307:   PetscCheck(dim >= 1, PetscObjectComm((PetscObject)dm), PETSC_ERR_USER, "Dimension must be 1,2,3 - found %" PetscInt_FMT, dim);
2308:   PetscCheck(dim <= 3, PetscObjectComm((PetscObject)dm), PETSC_ERR_USER, "Dimension must be 1,2,3 - found %" PetscInt_FMT, dim);
2309:   PetscFunctionReturn(PETSC_SUCCESS);
2310: }

2312: /*@
2313:   DMSwarmSetPointCoordinatesRandom - Sets initial coordinates for particles in each cell

2315:   Collective

2317:   Input Parameters:
2318: + dm  - the `DMSWARM`
2319: - Npc - The number of particles per cell in the cell `DM`

2321:   Level: intermediate

2323:   Notes:
2324:   The user must use `DMSwarmSetCellDM()` to set the cell `DM` first. The particles are placed randomly inside each cell. If only
2325:   one particle is in each cell, it is placed at the centroid.

2327: .seealso: `DM`, `DMSWARM`, `DMSwarmSetCellDM()`
2328: @*/
2329: PetscErrorCode DMSwarmSetPointCoordinatesRandom(DM dm, PetscInt Npc)
2330: {
2331:   DM             cdm;
2332:   DMSwarmCellDM  celldm;
2333:   PetscRandom    rnd;
2334:   DMPolytopeType ct;
2335:   PetscBool      simplex;
2336:   PetscReal     *centroid, *coords, *xi0, *v0, *J, *invJ, detJ;
2337:   PetscInt       dim, d, cStart, cEnd, c, p, Nfc;
2338:   const char   **coordFields;

2340:   PetscFunctionBeginUser;
2341:   PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)dm), &rnd));
2342:   PetscCall(PetscRandomSetInterval(rnd, -1.0, 1.0));
2343:   PetscCall(PetscRandomSetType(rnd, PETSCRAND48));

2345:   PetscCall(DMSwarmGetCellDMActive(dm, &celldm));
2346:   PetscCall(DMSwarmCellDMGetCoordinateFields(celldm, &Nfc, &coordFields));
2347:   PetscCheck(Nfc == 1, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "We only support a single coordinate field right now, not %" PetscInt_FMT, Nfc);
2348:   PetscCall(DMSwarmGetCellDM(dm, &cdm));
2349:   PetscCall(DMGetDimension(cdm, &dim));
2350:   PetscCall(DMPlexGetHeightStratum(cdm, 0, &cStart, &cEnd));
2351:   PetscCall(DMPlexGetCellType(cdm, cStart, &ct));
2352:   simplex = DMPolytopeTypeGetNumVertices(ct) == DMPolytopeTypeGetDim(ct) + 1 ? PETSC_TRUE : PETSC_FALSE;

2354:   PetscCall(PetscMalloc5(dim, &centroid, dim, &xi0, dim, &v0, dim * dim, &J, dim * dim, &invJ));
2355:   for (d = 0; d < dim; ++d) xi0[d] = -1.0;
2356:   PetscCall(DMSwarmGetField(dm, coordFields[0], NULL, NULL, (void **)&coords));
2357:   for (c = cStart; c < cEnd; ++c) {
2358:     if (Npc == 1) {
2359:       PetscCall(DMPlexComputeCellGeometryFVM(cdm, c, NULL, centroid, NULL));
2360:       for (d = 0; d < dim; ++d) coords[c * dim + d] = centroid[d];
2361:     } else {
2362:       PetscCall(DMPlexComputeCellGeometryFEM(cdm, c, NULL, v0, J, invJ, &detJ)); /* affine */
2363:       for (p = 0; p < Npc; ++p) {
2364:         const PetscInt n   = c * Npc + p;
2365:         PetscReal      sum = 0.0, refcoords[3];

2367:         for (d = 0; d < dim; ++d) {
2368:           PetscCall(PetscRandomGetValueReal(rnd, &refcoords[d]));
2369:           sum += refcoords[d];
2370:         }
2371:         if (simplex && sum > 0.0)
2372:           for (d = 0; d < dim; ++d) refcoords[d] -= PetscSqrtReal(dim) * sum;
2373:         CoordinatesRefToReal(dim, dim, xi0, v0, J, refcoords, &coords[n * dim]);
2374:       }
2375:     }
2376:   }
2377:   PetscCall(DMSwarmRestoreField(dm, coordFields[0], NULL, NULL, (void **)&coords));
2378:   PetscCall(PetscFree5(centroid, xi0, v0, J, invJ));
2379:   PetscCall(PetscRandomDestroy(&rnd));
2380:   PetscFunctionReturn(PETSC_SUCCESS);
2381: }

2383: /*@
2384:   DMSwarmGetType - Get particular flavor of `DMSWARM`

2386:   Collective

2388:   Input Parameter:
2389: . sw - the `DMSWARM`

2391:   Output Parameter:
2392: . stype - the `DMSWARM` type (e.g. `DMSWARM_PIC`)

2394:   Level: advanced

2396: .seealso: `DM`, `DMSWARM`, `DMSwarmSetMigrateType()`, `DMSwarmSetCollectType()`, `DMSwarmType`, `DMSWARM_PIC`, `DMSWARM_BASIC`
2397: @*/
2398: PetscErrorCode DMSwarmGetType(DM sw, DMSwarmType *stype)
2399: {
2400:   DM_Swarm *swarm = (DM_Swarm *)sw->data;

2402:   PetscFunctionBegin;
2404:   PetscAssertPointer(stype, 2);
2405:   *stype = swarm->swarm_type;
2406:   PetscFunctionReturn(PETSC_SUCCESS);
2407: }

2409: /*@
2410:   DMSwarmSetType - Set particular flavor of `DMSWARM`

2412:   Collective

2414:   Input Parameters:
2415: + sw    - the `DMSWARM`
2416: - stype - the `DMSWARM` type (e.g. `DMSWARM_PIC`)

2418:   Level: advanced

2420: .seealso: `DM`, `DMSWARM`, `DMSwarmSetMigrateType()`, `DMSwarmSetCollectType()`, `DMSwarmType`, `DMSWARM_PIC`, `DMSWARM_BASIC`
2421: @*/
2422: PetscErrorCode DMSwarmSetType(DM sw, DMSwarmType stype)
2423: {
2424:   DM_Swarm *swarm = (DM_Swarm *)sw->data;

2426:   PetscFunctionBegin;
2428:   swarm->swarm_type = stype;
2429:   if (swarm->swarm_type == DMSWARM_PIC) PetscCall(DMSwarmSetUpPIC(sw));
2430:   PetscFunctionReturn(PETSC_SUCCESS);
2431: }

2433: static PetscErrorCode DMSwarmCreateRemapDM_Private(DM sw, DM *rdm)
2434: {
2435:   PetscFE        fe;
2436:   DMPolytopeType ct;
2437:   PetscInt       dim, cStart;
2438:   const char    *prefix = "remap_";

2440:   PetscFunctionBegin;
2441:   PetscCall(DMCreate(PetscObjectComm((PetscObject)sw), rdm));
2442:   PetscCall(DMSetType(*rdm, DMPLEX));
2443:   PetscCall(DMPlexSetOptionsPrefix(*rdm, prefix));
2444:   PetscCall(DMSetFromOptions(*rdm));
2445:   PetscCall(PetscObjectSetName((PetscObject)*rdm, "remap"));
2446:   PetscCall(DMViewFromOptions(*rdm, NULL, "-dm_view"));

2448:   PetscCall(DMGetDimension(*rdm, &dim));
2449:   PetscCall(DMPlexGetHeightStratum(*rdm, 0, &cStart, NULL));
2450:   PetscCall(DMPlexGetCellType(*rdm, cStart, &ct));
2451:   PetscCall(PetscFECreateByCell(PETSC_COMM_SELF, dim, 1, ct, prefix, PETSC_DETERMINE, &fe));
2452:   PetscCall(PetscObjectSetName((PetscObject)fe, "distribution"));
2453:   PetscCall(DMSetField(*rdm, 0, NULL, (PetscObject)fe));
2454:   PetscCall(DMCreateDS(*rdm));
2455:   PetscCall(PetscFEDestroy(&fe));
2456:   PetscFunctionReturn(PETSC_SUCCESS);
2457: }

2459: static PetscErrorCode DMSetup_Swarm(DM sw)
2460: {
2461:   DM_Swarm *swarm = (DM_Swarm *)sw->data;

2463:   PetscFunctionBegin;
2464:   if (swarm->issetup) PetscFunctionReturn(PETSC_SUCCESS);
2465:   swarm->issetup = PETSC_TRUE;

2467:   if (swarm->remap_type != DMSWARM_REMAP_NONE) {
2468:     DMSwarmCellDM celldm;

2470:     PetscCall(DMSwarmGetCellDMByName(sw, "remap", &celldm));
2471:     if (!celldm) {
2472:       DM          rdm;
2473:       const char *fieldnames[2]  = {DMSwarmPICField_coor, "velocity"};
2474:       const char *vfieldnames[1] = {"w_q"};

2476:       PetscCall(DMSwarmCreateRemapDM_Private(sw, &rdm));
2477:       PetscCall(DMSwarmCellDMCreate(rdm, 1, vfieldnames, 2, fieldnames, &celldm));
2478:       PetscCall(DMSwarmAddCellDM(sw, celldm));
2479:       PetscCall(DMSwarmCellDMDestroy(&celldm));
2480:       PetscCall(DMDestroy(&rdm));
2481:     }
2482:   }

2484:   if (swarm->swarm_type == DMSWARM_PIC) {
2485:     DMSwarmCellDM celldm;

2487:     PetscCall(DMSwarmGetCellDMActive(sw, &celldm));
2488:     PetscCheck(celldm, PetscObjectComm((PetscObject)sw), PETSC_ERR_USER, "No active cell DM. DMSWARM_PIC requires you call DMSwarmSetCellDM() or DMSwarmAddCellDM()");
2489:     if (celldm->dm->ops->locatepointssubdomain) {
2490:       /* check methods exists for exact ownership identificiation */
2491:       PetscCall(PetscInfo(sw, "DMSWARM_PIC: Using method CellDM->ops->LocatePointsSubdomain\n"));
2492:       swarm->migrate_type = DMSWARM_MIGRATE_DMCELLEXACT;
2493:     } else {
2494:       /* check methods exist for point location AND rank neighbor identification */
2495:       PetscCheck(celldm->dm->ops->locatepoints, PetscObjectComm((PetscObject)sw), PETSC_ERR_USER, "DMSWARM_PIC requires the method CellDM->ops->locatepoints be defined");
2496:       PetscCall(PetscInfo(sw, "DMSWARM_PIC: Using method CellDM->LocatePoints\n"));

2498:       PetscCheck(celldm->dm->ops->getneighbors, PetscObjectComm((PetscObject)sw), PETSC_ERR_USER, "DMSWARM_PIC requires the method CellDM->ops->getneighbors be defined");
2499:       PetscCall(PetscInfo(sw, "DMSWARM_PIC: Using method CellDM->GetNeigbors\n"));

2501:       swarm->migrate_type = DMSWARM_MIGRATE_DMCELLNSCATTER;
2502:     }
2503:   }

2505:   PetscCall(DMSwarmFinalizeFieldRegister(sw));

2507:   /* check some fields were registered */
2508:   PetscCheck(swarm->db->nfields > 2, PetscObjectComm((PetscObject)sw), PETSC_ERR_USER, "At least one field user must be registered via DMSwarmRegisterXXX()");
2509:   PetscFunctionReturn(PETSC_SUCCESS);
2510: }

2512: static PetscErrorCode DMDestroy_Swarm(DM dm)
2513: {
2514:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

2516:   PetscFunctionBegin;
2517:   if (--swarm->refct > 0) PetscFunctionReturn(PETSC_SUCCESS);
2518:   PetscCall(PetscObjectListDestroy(&swarm->cellDMs));
2519:   PetscCall(PetscFree(swarm->activeCellDM));
2520:   PetscCall(DMSwarmDataBucketDestroy(&swarm->db));
2521:   PetscCall(PetscFree(swarm));
2522:   PetscFunctionReturn(PETSC_SUCCESS);
2523: }

2525: static PetscErrorCode DMSwarmView_Draw(DM dm, PetscViewer viewer)
2526: {
2527:   DM            cdm;
2528:   DMSwarmCellDM celldm;
2529:   PetscDraw     draw;
2530:   PetscReal    *coords, oldPause, radius = 0.01;
2531:   PetscInt      Np, p, bs, Nfc;
2532:   const char  **coordFields;

2534:   PetscFunctionBegin;
2535:   PetscCall(PetscOptionsGetReal(NULL, ((PetscObject)dm)->prefix, "-dm_view_swarm_radius", &radius, NULL));
2536:   PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
2537:   PetscCall(DMSwarmGetCellDM(dm, &cdm));
2538:   PetscCall(PetscDrawGetPause(draw, &oldPause));
2539:   PetscCall(PetscDrawSetPause(draw, 0.0));
2540:   PetscCall(DMView(cdm, viewer));
2541:   PetscCall(PetscDrawSetPause(draw, oldPause));

2543:   PetscCall(DMSwarmGetCellDMActive(dm, &celldm));
2544:   PetscCall(DMSwarmCellDMGetCoordinateFields(celldm, &Nfc, &coordFields));
2545:   PetscCheck(Nfc == 1, PetscObjectComm((PetscObject)dm), PETSC_ERR_SUP, "We only support a single coordinate field right now, not %" PetscInt_FMT, Nfc);
2546:   PetscCall(DMSwarmGetLocalSize(dm, &Np));
2547:   PetscCall(DMSwarmGetField(dm, coordFields[0], &bs, NULL, (void **)&coords));
2548:   for (p = 0; p < Np; ++p) {
2549:     const PetscInt i = p * bs;

2551:     PetscCall(PetscDrawEllipse(draw, coords[i], coords[i + 1], radius, radius, PETSC_DRAW_BLUE));
2552:   }
2553:   PetscCall(DMSwarmRestoreField(dm, coordFields[0], &bs, NULL, (void **)&coords));
2554:   PetscCall(PetscDrawFlush(draw));
2555:   PetscCall(PetscDrawPause(draw));
2556:   PetscCall(PetscDrawSave(draw));
2557:   PetscFunctionReturn(PETSC_SUCCESS);
2558: }

2560: static PetscErrorCode DMView_Swarm_Ascii(DM dm, PetscViewer viewer)
2561: {
2562:   PetscViewerFormat format;
2563:   PetscDataType     wtype = PETSC_DATATYPE_UNKNOWN;
2564:   PetscInt         *sizes;
2565:   PetscInt          dim, Np, wbs = 0, maxSize = 17;
2566:   MPI_Comm          comm;
2567:   PetscMPIInt       rank, size;
2568:   const char       *name, *cellid;

2570:   PetscFunctionBegin;
2571:   PetscCall(PetscViewerGetFormat(viewer, &format));
2572:   PetscCall(DMGetDimension(dm, &dim));
2573:   PetscCall(DMSwarmGetLocalSize(dm, &Np));
2574:   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
2575:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
2576:   PetscCallMPI(MPI_Comm_size(comm, &size));
2577:   PetscCall(PetscObjectGetName((PetscObject)dm, &name));
2578:   if (name) PetscCall(PetscViewerASCIIPrintf(viewer, "%s in %" PetscInt_FMT " dimension%s:\n", name, dim, dim == 1 ? "" : "s"));
2579:   else PetscCall(PetscViewerASCIIPrintf(viewer, "Swarm in %" PetscInt_FMT " dimension%s:\n", dim, dim == 1 ? "" : "s"));
2580:   if (size < maxSize) PetscCall(PetscCalloc1(size, &sizes));
2581:   else PetscCall(PetscCalloc1(3, &sizes));
2582:   if (size < maxSize) {
2583:     PetscCallMPI(MPI_Gather(&Np, 1, MPIU_INT, sizes, 1, MPIU_INT, 0, comm));
2584:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Number of particles per rank:"));
2585:     for (PetscInt p = 0; p < size; ++p) {
2586:       if (rank == 0) PetscCall(PetscViewerASCIIPrintf(viewer, " %" PetscInt_FMT, sizes[p]));
2587:     }
2588:   } else {
2589:     PetscInt locMinMax[2] = {Np, Np};

2591:     PetscCall(PetscGlobalMinMaxInt(comm, locMinMax, sizes));
2592:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Min/Max of particles per rank: %" PetscInt_FMT "/%" PetscInt_FMT, sizes[0], sizes[1]));
2593:   }
2594:   PetscCall(PetscViewerASCIIPrintf(viewer, "\n"));
2595:   PetscCall(PetscFree(sizes));
2596:   if (format == PETSC_VIEWER_ASCII_INFO) {
2597:     DM_Swarm     *sw = (DM_Swarm *)dm->data;
2598:     DMSwarmCellDM celldm;
2599:     PetscInt     *cell;
2600:     PetscBool     hasWeight;
2601:     const char   *fname = "w_q";

2603:     PetscCall(DMSwarmDataFieldStringInList(fname, sw->db->nfields, (const DMSwarmDataField *)sw->db->field, &hasWeight));
2604:     if (hasWeight) {
2605:       PetscCall(DMSwarmGetFieldInfo(dm, fname, &wbs, &wtype));
2606:       PetscCheck(wtype == PETSC_REAL || wtype == PETSC_SCALAR, comm, PETSC_ERR_SUP, "Weight field %s must have type PETSC_REAL or PETSC_SCALAR, not %s", fname, PetscDataTypes[wtype]);
2607:       PetscCheck(wbs == 1, comm, PETSC_ERR_ARG_WRONG, "Weight field %s must have block size 1, not %" PetscInt_FMT, fname, wbs);
2608:     }
2609:     PetscCall(PetscViewerASCIIPrintf(viewer, "  Cells containing each particle:\n"));
2610:     PetscCall(PetscViewerASCIIPushSynchronized(viewer));
2611:     PetscCall(DMSwarmGetCellDMActive(dm, &celldm));
2612:     PetscCall(DMSwarmCellDMGetCellID(celldm, &cellid));
2613:     PetscCall(DMSwarmGetField(dm, cellid, NULL, NULL, (void **)&cell));
2614:     if (hasWeight) {
2615:       PetscReal  **coords;
2616:       void        *weight;
2617:       PetscInt     Ncf, *bsC;
2618:       const char **coordNames;

2620:       PetscCall(DMSwarmCellDMGetCoordinateFields(celldm, &Ncf, &coordNames));
2621:       PetscCall(PetscMalloc2(Ncf, &coords, Ncf, &bsC));
2622:       for (PetscInt n = 0; n < Ncf; ++n) PetscCall(DMSwarmGetField(dm, coordNames[n], &bsC[n], NULL, (void **)&coords[n]));
2623:       PetscCall(DMSwarmGetField(dm, fname, NULL, NULL, &weight));
2624:       for (PetscInt p = 0; p < Np; ++p) {
2625:         PetscReal wp;

2627:         if (wtype == PETSC_REAL) wp = ((PetscReal *)weight)[p];
2628:         else wp = PetscRealPart(((PetscScalar *)weight)[p]);
2629:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "  p%" PetscInt_FMT ": %" PetscInt_FMT " wt: %g x: (", p, cell[p], (double)wp));
2630:         for (PetscInt n = 0; n < Ncf; ++n) {
2631:           if (n > 0) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ", "));
2632:           for (PetscInt d = 0; d < bsC[n]; ++d) {
2633:             if (d > 0) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ", "));
2634:             PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%g", (double)coords[n][p * bsC[n] + d]));
2635:           }
2636:         }
2637:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, ")\n"));
2638:       }
2639:       PetscCall(DMSwarmRestoreField(dm, fname, NULL, NULL, &weight));
2640:       for (PetscInt n = 0; n < Ncf; ++n) PetscCall(DMSwarmRestoreField(dm, coordNames[n], &bsC[n], NULL, (void **)&coords[n]));
2641:       PetscCall(PetscFree2(coords, bsC));
2642:     } else {
2643:       for (PetscInt p = 0; p < Np; ++p) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "  p%" PetscInt_FMT ": %" PetscInt_FMT "\n", p, cell[p]));
2644:     }
2645:     PetscCall(DMSwarmRestoreField(dm, cellid, NULL, NULL, (void **)&cell));
2646:     PetscCall(PetscViewerFlush(viewer));
2647:     PetscCall(PetscViewerASCIIPopSynchronized(viewer));
2648:   }
2649:   PetscFunctionReturn(PETSC_SUCCESS);
2650: }

2652: static PetscErrorCode DMView_Swarm(DM dm, PetscViewer viewer)
2653: {
2654:   DM_Swarm *swarm = (DM_Swarm *)dm->data;
2655:   PetscBool isascii, ibinary, isvtk, isdraw, ispython;
2656: #if PetscDefined(HAVE_HDF5)
2657:   PetscBool ishdf5;
2658: #endif

2660:   PetscFunctionBegin;
2663:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
2664:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &ibinary));
2665:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERVTK, &isvtk));
2666: #if PetscDefined(HAVE_HDF5)
2667:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
2668: #endif
2669:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
2670:   PetscCall(PetscObjectHasFunction((PetscObject)viewer, "PetscViewerPythonViewObject_C", &ispython));
2671:   if (isascii) {
2672:     PetscViewerFormat format;

2674:     PetscCall(PetscViewerGetFormat(viewer, &format));
2675:     switch (format) {
2676:     case PETSC_VIEWER_ASCII_INFO_DETAIL:
2677:       PetscCall(DMSwarmDataBucketView(PetscObjectComm((PetscObject)dm), swarm->db, NULL, DATABUCKET_VIEW_STDOUT));
2678:       break;
2679:     default:
2680:       PetscCall(DMView_Swarm_Ascii(dm, viewer));
2681:     }
2682:   } else {
2683: #if PetscDefined(HAVE_HDF5)
2684:     if (ishdf5) PetscCall(DMSwarmView_HDF5(dm, viewer));
2685: #endif
2686:     if (isdraw) PetscCall(DMSwarmView_Draw(dm, viewer));
2687:     if (ispython) PetscCall(PetscViewerPythonViewObject(viewer, (PetscObject)dm));
2688:   }
2689:   PetscFunctionReturn(PETSC_SUCCESS);
2690: }

2692: /*@
2693:   DMSwarmGetCellSwarm - Extracts a single cell from the `DMSWARM` object, returns it as a single cell `DMSWARM`.
2694:   The cell `DM` is filtered for fields of that cell, and the filtered `DM` is used as the cell `DM` of the new swarm object.

2696:   Noncollective

2698:   Input Parameters:
2699: + sw        - the `DMSWARM`
2700: . cellID    - the integer id of the cell to be extracted and filtered
2701: - cellswarm - The `DMSWARM` to receive the cell

2703:   Level: beginner

2705:   Notes:
2706:   This presently only supports `DMSWARM_PIC` type

2708:   Should be restored with `DMSwarmRestoreCellSwarm()`

2710:   Changes to this cell of the swarm will be lost if they are made prior to restoring this cell.

2712: .seealso: `DM`, `DMSWARM`, `DMSwarmRestoreCellSwarm()`
2713: @*/
2714: PetscErrorCode DMSwarmGetCellSwarm(DM sw, PetscInt cellID, DM cellswarm)
2715: {
2716:   DM_Swarm   *original = (DM_Swarm *)sw->data;
2717:   DMLabel     label;
2718:   DM          dmc, subdmc;
2719:   PetscInt   *pids, particles, dim;
2720:   const char *name;

2722:   PetscFunctionBegin;
2723:   /* Configure new swarm */
2724:   PetscCall(DMSetType(cellswarm, DMSWARM));
2725:   PetscCall(DMGetDimension(sw, &dim));
2726:   PetscCall(DMSetDimension(cellswarm, dim));
2727:   PetscCall(DMSwarmSetType(cellswarm, DMSWARM_PIC));
2728:   /* Destroy the unused, unconfigured data bucket to prevent stragglers in memory */
2729:   PetscCall(DMSwarmDataBucketDestroy(&((DM_Swarm *)cellswarm->data)->db));
2730:   PetscCall(DMSwarmSortGetAccess(sw));
2731:   PetscCall(DMSwarmSortGetNumberOfPointsPerCell(sw, cellID, &particles));
2732:   PetscCall(DMSwarmSortGetPointsPerCell(sw, cellID, &particles, &pids));
2733:   PetscCall(DMSwarmDataBucketCreateFromSubset(original->db, particles, pids, &((DM_Swarm *)cellswarm->data)->db));
2734:   PetscCall(DMSwarmSortRestoreAccess(sw));
2735:   PetscCall(DMSwarmSortRestorePointsPerCell(sw, cellID, &particles, &pids));
2736:   PetscCall(DMSwarmGetCellDM(sw, &dmc));
2737:   PetscCall(DMLabelCreate(PetscObjectComm((PetscObject)sw), "singlecell", &label));
2738:   PetscCall(DMAddLabel(dmc, label));
2739:   PetscCall(DMLabelSetValue(label, cellID, 1));
2740:   PetscCall(DMPlexFilter(dmc, label, 1, PETSC_FALSE, PETSC_FALSE, PetscObjectComm((PetscObject)dmc), NULL, &subdmc));
2741:   PetscCall(PetscObjectGetName((PetscObject)dmc, &name));
2742:   PetscCall(PetscObjectSetName((PetscObject)subdmc, name));
2743:   PetscCall(DMSwarmSetCellDM(cellswarm, subdmc));
2744:   PetscCall(DMLabelDestroy(&label));
2745:   PetscFunctionReturn(PETSC_SUCCESS);
2746: }

2748: /*@
2749:   DMSwarmRestoreCellSwarm - Restores a `DMSWARM` object obtained with `DMSwarmGetCellSwarm()`. All fields are copied back into the parent swarm.

2751:   Noncollective

2753:   Input Parameters:
2754: + sw        - the parent `DMSWARM`
2755: . cellID    - the integer id of the cell to be copied back into the parent swarm
2756: - cellswarm - the cell swarm object

2758:   Level: beginner

2760:   Note:
2761:   This only supports `DMSWARM_PIC` types of `DMSWARM`s

2763: .seealso: `DM`, `DMSWARM`, `DMSwarmGetCellSwarm()`
2764: @*/
2765: PetscErrorCode DMSwarmRestoreCellSwarm(DM sw, PetscInt cellID, DM cellswarm)
2766: {
2767:   DM        dmc;
2768:   PetscInt *pids, particles, p;

2770:   PetscFunctionBegin;
2771:   PetscCall(DMSwarmSortGetAccess(sw));
2772:   PetscCall(DMSwarmSortGetPointsPerCell(sw, cellID, &particles, &pids));
2773:   PetscCall(DMSwarmSortRestoreAccess(sw));
2774:   /* Pointwise copy of each particle based on pid. The parent swarm may not be altered during this process. */
2775:   for (p = 0; p < particles; ++p) PetscCall(DMSwarmDataBucketCopyPoint(((DM_Swarm *)cellswarm->data)->db, pids[p], ((DM_Swarm *)sw->data)->db, pids[p]));
2776:   /* Free memory, destroy cell dm */
2777:   PetscCall(DMSwarmGetCellDM(cellswarm, &dmc));
2778:   PetscCall(DMDestroy(&dmc));
2779:   PetscCall(DMSwarmSortRestorePointsPerCell(sw, cellID, &particles, &pids));
2780:   PetscFunctionReturn(PETSC_SUCCESS);
2781: }

2783: /*@
2784:   DMSwarmComputeMoments - Compute the first three particle moments for a given field

2786:   Noncollective

2788:   Input Parameters:
2789: + sw         - the `DMSWARM`
2790: . coordinate - the coordinate field name
2791: - weight     - the weight field name

2793:   Output Parameter:
2794: . moments - the field moments

2796:   Level: intermediate

2798:   Notes:
2799:   The `moments` array should be of length bs + 2, where bs is the block size of the coordinate field.

2801:   The weight field must have blocksize 1 and data type `PETSC_REAL` or `PETSC_SCALAR`. For complex scalars,
2802:   only the real part of each weight is used.

2804: .seealso: `DM`, `DMSWARM`, `DMPlexComputeMoments()`
2805: @*/
2806: PetscErrorCode DMSwarmComputeMoments(DM sw, const char coordinate[], const char weight[], PetscReal moments[])
2807: {
2808:   const PetscReal *coords;
2809:   void            *weights;
2810:   PetscDataType    dtc, dtw;
2811:   PetscInt         bsc, bsw, Np;
2812:   MPI_Comm         comm;

2814:   PetscFunctionBegin;
2816:   PetscAssertPointer(coordinate, 2);
2817:   PetscAssertPointer(weight, 3);
2818:   PetscAssertPointer(moments, 4);
2819:   PetscCall(PetscObjectGetComm((PetscObject)sw, &comm));
2820:   PetscCall(DMSwarmGetFieldInfo(sw, coordinate, &bsc, &dtc));
2821:   PetscCall(DMSwarmGetFieldInfo(sw, weight, &bsw, &dtw));
2822:   PetscCheck(dtc == PETSC_REAL, comm, PETSC_ERR_ARG_WRONG, "Coordinate field %s must be real, not %s", coordinate, PetscDataTypes[dtc]);
2823:   PetscCheck(dtw == PETSC_REAL || dtw == PETSC_SCALAR, comm, PETSC_ERR_ARG_WRONG, "Weight field %s must have type PETSC_REAL or PETSC_SCALAR, not %s", weight, PetscDataTypes[dtw]);
2824:   PetscCheck(bsw == 1, comm, PETSC_ERR_ARG_WRONG, "Weight field %s must be a scalar, not blocksize %" PetscInt_FMT, weight, bsw);
2825:   PetscCall(DMSwarmGetField(sw, coordinate, NULL, NULL, (void **)&coords));
2826:   PetscCall(DMSwarmGetField(sw, weight, NULL, NULL, &weights));
2827:   PetscCall(DMSwarmGetLocalSize(sw, &Np));
2828:   PetscCall(PetscArrayzero(moments, bsc + 2));
2829:   for (PetscInt p = 0; p < Np; ++p) {
2830:     const PetscReal *c = &coords[p * bsc];
2831:     PetscReal        wp;

2833:     if (dtw == PETSC_REAL) wp = ((PetscReal *)weights)[p];
2834:     else wp = PetscRealPart(((PetscScalar *)weights)[p]);
2835:     moments[0] += wp;
2836:     for (PetscInt d = 0; d < bsc; ++d) {
2837:       moments[d + 1] += wp * c[d];
2838:       moments[bsc + 1] += wp * PetscSqr(c[d]);
2839:     }
2840:   }
2841:   PetscCall(DMSwarmRestoreField(sw, coordinate, NULL, NULL, (void **)&coords));
2842:   PetscCall(DMSwarmRestoreField(sw, weight, NULL, NULL, &weights));
2843:   PetscCallMPI(MPIU_Allreduce(MPI_IN_PLACE, moments, bsc + 2, MPIU_REAL, MPI_SUM, PetscObjectComm((PetscObject)sw)));
2844:   PetscFunctionReturn(PETSC_SUCCESS);
2845: }

2847: static PetscErrorCode DMSetFromOptions_Swarm(DM dm, PetscOptionItems PetscOptionsObject)
2848: {
2849:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

2851:   PetscFunctionBegin;
2852:   PetscOptionsHeadBegin(PetscOptionsObject, "DMSwarm Options");
2853:   PetscCall(PetscOptionsEnum("-dm_swarm_remap_type", "Remap algorithm", "DMSwarmSetRemapType", DMSwarmRemapTypeNames, (PetscEnum)swarm->remap_type, (PetscEnum *)&swarm->remap_type, NULL));
2854:   PetscOptionsHeadEnd();
2855:   PetscFunctionReturn(PETSC_SUCCESS);
2856: }

2858: PETSC_INTERN PetscErrorCode DMClone_Swarm(DM, DM *);

2860: static PetscErrorCode DMInitialize_Swarm(DM sw)
2861: {
2862:   PetscFunctionBegin;
2863:   sw->ops->view                     = DMView_Swarm;
2864:   sw->ops->load                     = NULL;
2865:   sw->ops->setfromoptions           = DMSetFromOptions_Swarm;
2866:   sw->ops->clone                    = DMClone_Swarm;
2867:   sw->ops->setup                    = DMSetup_Swarm;
2868:   sw->ops->createlocalsection       = NULL;
2869:   sw->ops->createsectionpermutation = NULL;
2870:   sw->ops->createdefaultconstraints = NULL;
2871:   sw->ops->createglobalvector       = DMCreateGlobalVector_Swarm;
2872:   sw->ops->createlocalvector        = DMCreateLocalVector_Swarm;
2873:   sw->ops->getlocaltoglobalmapping  = NULL;
2874:   sw->ops->createfieldis            = NULL;
2875:   sw->ops->createcoordinatedm       = NULL;
2876:   sw->ops->createcellcoordinatedm   = NULL;
2877:   sw->ops->getcoloring              = NULL;
2878:   sw->ops->creatematrix             = DMCreateMatrix_Swarm;
2879:   sw->ops->createinterpolation      = NULL;
2880:   sw->ops->createinjection          = NULL;
2881:   sw->ops->createmassmatrix         = DMCreateMassMatrix_Swarm;
2882:   sw->ops->creategradientmatrix     = DMCreateGradientMatrix_Swarm;
2883:   sw->ops->refine                   = NULL;
2884:   sw->ops->coarsen                  = NULL;
2885:   sw->ops->refinehierarchy          = NULL;
2886:   sw->ops->coarsenhierarchy         = NULL;
2887:   sw->ops->globaltolocalbegin       = DMGlobalToLocalBegin_Swarm;
2888:   sw->ops->globaltolocalend         = DMGlobalToLocalEnd_Swarm;
2889:   sw->ops->localtoglobalbegin       = DMLocalToGlobalBegin_Swarm;
2890:   sw->ops->localtoglobalend         = DMLocalToGlobalEnd_Swarm;
2891:   sw->ops->destroy                  = DMDestroy_Swarm;
2892:   sw->ops->createsubdm              = NULL;
2893:   sw->ops->getdimpoints             = NULL;
2894:   sw->ops->locatepoints             = NULL;
2895:   sw->ops->projectfieldlocal        = DMProjectFieldLocal_Swarm;
2896:   PetscFunctionReturn(PETSC_SUCCESS);
2897: }

2899: PETSC_INTERN PetscErrorCode DMClone_Swarm(DM dm, DM *newdm)
2900: {
2901:   DM_Swarm *swarm = (DM_Swarm *)dm->data;

2903:   PetscFunctionBegin;
2904:   swarm->refct++;
2905:   (*newdm)->data = swarm;
2906:   PetscCall(PetscObjectChangeTypeName((PetscObject)*newdm, DMSWARM));
2907:   PetscCall(DMInitialize_Swarm(*newdm));
2908:   (*newdm)->dim = dm->dim;
2909:   PetscFunctionReturn(PETSC_SUCCESS);
2910: }

2912: /*MC
2913:  DMSWARM = "swarm" - A `DM` object for particle methods, such as particle-in-cell (PIC), in which the underlying
2914:            data is both (i) dynamic in length, (ii) and of arbitrary data type.

2916:  Level: intermediate

2918:  Notes:
2919:  User data can be represented by `DMSWARM` through a registering "fields" which are to be stored on particles.
2920:  To register a field, the user must provide;
2921:  (a) a unique name;
2922:  (b) the data type (or size in bytes);
2923:  (c) the block size of the data.

2925:  For example, suppose the application requires a unique id, energy, momentum and density to be stored
2926:  on a set of particles. Then the following code could be used
2927: .vb
2928:     DMSwarmInitializeFieldRegister(dm)
2929:     DMSwarmRegisterPetscDatatypeField(dm,"uid",1,PETSC_LONG);
2930:     DMSwarmRegisterPetscDatatypeField(dm,"energy",1,PETSC_REAL);
2931:     DMSwarmRegisterPetscDatatypeField(dm,"momentum",3,PETSC_REAL);
2932:     DMSwarmRegisterPetscDatatypeField(dm,"density",1,PETSC_FLOAT);
2933:     DMSwarmFinalizeFieldRegister(dm)
2934: .ve

2936:  The fields represented by `DMSWARM` are dynamic and can be re-sized at any time.
2937:  The only restriction imposed by `DMSWARM` is that all fields contain the same number of particles.

2939:  To support particle methods, "migration" techniques are provided. These methods migrate data
2940:  between ranks.

2942:  `DMSWARM` supports the methods `DMCreateGlobalVector()` and `DMCreateLocalVector()`.
2943:  As a `DMSWARM` may internally define and store values of different data types,
2944:  before calling `DMCreateGlobalVector()` or `DMCreateLocalVector()`, the user must inform `DMSWARM` which
2945:  fields should be used to define a `Vec` object via `DMSwarmVectorDefineField()`
2946:  The specified field can be changed at any time - thereby permitting vectors
2947:  compatible with different fields to be created.

2949:  A dual representation of fields in the `DMSWARM` and a Vec object is permitted via `DMSwarmCreateGlobalVectorFromField()`
2950:  Here the data defining the field in the `DMSWARM` is shared with a `Vec`.
2951:  This is inherently unsafe if you alter the size of the field at any time between
2952:  calls to `DMSwarmCreateGlobalVectorFromField()` and `DMSwarmDestroyGlobalVectorFromField()`.
2953:  If the local size of the `DMSWARM` does not match the local size of the global vector
2954:  when `DMSwarmDestroyGlobalVectorFromField()` is called, an error is thrown.

2956:  Additional high-level support is provided for Particle-In-Cell methods. Refer to `DMSwarmSetType()`.

2958: .seealso: `DM`, `DMSWARM`, `DMType`, `DMCreate()`, `DMSetType()`, `DMSwarmSetType()`, `DMSwarmType`, `DMSwarmCreateGlobalVectorFromField()`,
2959:          `DMCreateGlobalVector()`, `DMCreateLocalVector()`
2960: M*/

2962: PETSC_EXTERN PetscErrorCode DMCreate_Swarm(DM dm)
2963: {
2964:   DM_Swarm *swarm;

2966:   PetscFunctionBegin;
2968:   PetscCall(PetscNew(&swarm));
2969:   dm->data = swarm;
2970:   PetscCall(DMSwarmDataBucketCreate(&swarm->db));
2971:   PetscCall(DMSwarmInitializeFieldRegister(dm));
2972:   dm->dim                               = 0;
2973:   swarm->refct                          = 1;
2974:   swarm->issetup                        = PETSC_FALSE;
2975:   swarm->swarm_type                     = DMSWARM_BASIC;
2976:   swarm->migrate_type                   = DMSWARM_MIGRATE_BASIC;
2977:   swarm->collect_type                   = DMSWARM_COLLECT_BASIC;
2978:   swarm->migrate_error_on_missing_point = PETSC_FALSE;
2979:   swarm->collect_view_active            = PETSC_FALSE;
2980:   swarm->collect_view_reset_nlocal      = -1;
2981:   PetscCall(DMInitialize_Swarm(dm));
2982:   if (SwarmDataFieldId == -1) PetscCall(PetscObjectComposedDataRegister(&SwarmDataFieldId));
2983:   PetscFunctionReturn(PETSC_SUCCESS);
2984: }

2986: /* Replace dm with the contents of ndm, and then destroy ndm
2987:    - Share the DM_Swarm structure
2988: */
2989: /*@
2990:   DMSwarmReplace - Replace the internal state of a `DMSWARM` with that of another `DMSWARM`, sharing the underlying particle data and destroying the source `DM`.

2992:   Collective

2994:   Input Parameters:
2995: + dm  - the destination `DMSWARM`, whose current contents are discarded
2996: - ndm - pointer to the source `DMSWARM`; destroyed and set to `NULL` on return

2998:   Level: developer

3000:   Note:
3001:   The dimension, periodicity, name, and shared reference to the underlying particle bucket are transferred from the source to the destination.

3003: .seealso: `DM`, `DMSWARM`, `DMSwarmDuplicate()`, `DMDestroy()`
3004: @*/
3005: PetscErrorCode DMSwarmReplace(DM dm, DM *ndm)
3006: {
3007:   DM               dmNew = *ndm;
3008:   const PetscReal *maxCell, *Lstart, *L;
3009:   PetscInt         dim;

3011:   PetscFunctionBegin;
3012:   if (dm == dmNew) {
3013:     PetscCall(DMDestroy(ndm));
3014:     PetscFunctionReturn(PETSC_SUCCESS);
3015:   }
3016:   dm->setupcalled = dmNew->setupcalled;
3017:   if (!dm->hdr.name) {
3018:     const char *name;

3020:     PetscCall(PetscObjectGetName((PetscObject)*ndm, &name));
3021:     PetscCall(PetscObjectSetName((PetscObject)dm, name));
3022:   }
3023:   PetscCall(DMGetDimension(dmNew, &dim));
3024:   PetscCall(DMSetDimension(dm, dim));
3025:   PetscCall(DMGetPeriodicity(dmNew, &maxCell, &Lstart, &L));
3026:   PetscCall(DMSetPeriodicity(dm, maxCell, Lstart, L));
3027:   PetscCall(DMDestroy_Swarm(dm));
3028:   PetscCall(DMInitialize_Swarm(dm));
3029:   dm->data = dmNew->data;
3030:   ((DM_Swarm *)dmNew->data)->refct++;
3031:   PetscCall(DMDestroy(ndm));
3032:   PetscFunctionReturn(PETSC_SUCCESS);
3033: }

3035: /*@
3036:   DMSwarmDuplicate - Creates a new `DMSWARM` with the same fields and cell `DM`s but no particles

3038:   Collective

3040:   Input Parameter:
3041: . sw - the `DMSWARM`

3043:   Output Parameter:
3044: . nsw - the new `DMSWARM`

3046:   Level: beginner

3048: .seealso: `DM`, `DMSWARM`, `DMSwarmCreate()`, `DMClone()`
3049: @*/
3050: PetscErrorCode DMSwarmDuplicate(DM sw, DM *nsw)
3051: {
3052:   DM_Swarm         *swarm = (DM_Swarm *)sw->data;
3053:   DMSwarmDataField *fields;
3054:   DMSwarmCellDM     celldm, ncelldm;
3055:   DMSwarmType       stype;
3056:   const char       *name, **celldmnames;
3057:   void             *ctx;
3058:   PetscInt          dim, Nf, Ndm;
3059:   PetscBool         flg;

3061:   PetscFunctionBegin;
3062:   PetscCall(DMCreate(PetscObjectComm((PetscObject)sw), nsw));
3063:   PetscCall(DMSetType(*nsw, DMSWARM));
3064:   PetscCall(PetscObjectGetName((PetscObject)sw, &name));
3065:   PetscCall(PetscObjectSetName((PetscObject)*nsw, name));
3066:   PetscCall(DMGetDimension(sw, &dim));
3067:   PetscCall(DMSetDimension(*nsw, dim));
3068:   PetscCall(DMSwarmGetType(sw, &stype));
3069:   PetscCall(DMSwarmSetType(*nsw, stype));
3070:   PetscCall(DMGetApplicationContext(sw, &ctx));
3071:   PetscCall(DMSetApplicationContext(*nsw, ctx));

3073:   PetscCall(DMSwarmDataBucketGetDMSwarmDataFields(swarm->db, &Nf, &fields));
3074:   for (PetscInt f = 0; f < Nf; ++f) {
3075:     PetscCall(DMSwarmDataFieldStringInList(fields[f]->name, ((DM_Swarm *)(*nsw)->data)->db->nfields, (const DMSwarmDataField *)((DM_Swarm *)(*nsw)->data)->db->field, &flg));
3076:     if (!flg) PetscCall(DMSwarmRegisterPetscDatatypeField(*nsw, fields[f]->name, fields[f]->bs, fields[f]->petsc_type));
3077:   }

3079:   PetscCall(DMSwarmGetCellDMNames(sw, &Ndm, &celldmnames));
3080:   for (PetscInt c = 0; c < Ndm; ++c) {
3081:     DM           dm;
3082:     PetscInt     Ncf;
3083:     const char **coordfields, **fields;

3085:     PetscCall(DMSwarmGetCellDMByName(sw, celldmnames[c], &celldm));
3086:     PetscCall(DMSwarmCellDMGetDM(celldm, &dm));
3087:     PetscCall(DMSwarmCellDMGetCoordinateFields(celldm, &Ncf, &coordfields));
3088:     PetscCall(DMSwarmCellDMGetFields(celldm, &Nf, &fields));
3089:     PetscCall(DMSwarmCellDMCreate(dm, Nf, fields, Ncf, coordfields, &ncelldm));
3090:     PetscCall(DMSwarmAddCellDM(*nsw, ncelldm));
3091:     PetscCall(DMSwarmCellDMDestroy(&ncelldm));
3092:   }
3093:   PetscCall(PetscFree(celldmnames));

3095:   PetscCall(DMSetFromOptions(*nsw));
3096:   PetscCall(DMSetUp(*nsw));
3097:   PetscCall(DMSwarmGetCellDMActive(sw, &celldm));
3098:   PetscCall(PetscObjectGetName((PetscObject)celldm, &name));
3099:   PetscCall(DMSwarmSetCellDMActive(*nsw, name));
3100:   PetscFunctionReturn(PETSC_SUCCESS);
3101: }

3103: PetscErrorCode DMLocalToGlobalBegin_Swarm(DM dm, Vec l, InsertMode mode, Vec g)
3104: {
3105:   PetscFunctionBegin;
3106:   PetscFunctionReturn(PETSC_SUCCESS);
3107: }

3109: PetscErrorCode DMLocalToGlobalEnd_Swarm(DM dm, Vec l, InsertMode mode, Vec g)
3110: {
3111:   PetscFunctionBegin;
3112:   switch (mode) {
3113:   case INSERT_VALUES:
3114:     PetscCall(VecCopy(l, g));
3115:     break;
3116:   case ADD_VALUES:
3117:     PetscCall(VecAXPY(g, 1., l));
3118:     break;
3119:   default:
3120:     SETERRQ(PetscObjectComm((PetscObject)dm), PETSC_ERR_ARG_WRONG, "Mode not supported: %d", mode);
3121:   }
3122:   PetscFunctionReturn(PETSC_SUCCESS);
3123: }

3125: PetscErrorCode DMGlobalToLocalBegin_Swarm(DM dm, Vec g, InsertMode mode, Vec l)
3126: {
3127:   PetscFunctionBegin;
3128:   PetscFunctionReturn(PETSC_SUCCESS);
3129: }

3131: PetscErrorCode DMGlobalToLocalEnd_Swarm(DM dm, Vec g, InsertMode mode, Vec l)
3132: {
3133:   PetscFunctionBegin;
3134:   PetscCall(DMLocalToGlobalEnd_Swarm(dm, g, mode, l));
3135:   PetscFunctionReturn(PETSC_SUCCESS);
3136: }