Actual source code: general.c

  1: /*
  2:      Provides the functions for index sets (IS) defined by a list of integers.
  3: */
  4: #include <../src/vec/is/is/impls/general/general.h>
  5: #include <petsc/private/viewerhdf5impl.h>

  7: static PetscErrorCode ISDuplicate_General(IS is, IS *newIS)
  8: {
  9:   IS_General *sub = (IS_General *)is->data;
 10:   PetscInt    n, bs;

 12:   PetscFunctionBegin;
 13:   PetscCall(PetscLayoutGetLocalSize(is->map, &n));
 14:   PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)is), n, sub->idx, PETSC_COPY_VALUES, newIS));
 15:   PetscCall(PetscLayoutGetBlockSize(is->map, &bs));
 16:   PetscCall(PetscLayoutSetBlockSize((*newIS)->map, bs));
 17:   PetscFunctionReturn(PETSC_SUCCESS);
 18: }

 20: static PetscErrorCode ISDestroy_General(IS is)
 21: {
 22:   IS_General *is_general = (IS_General *)is->data;

 24:   PetscFunctionBegin;
 25:   if (is_general->allocated) PetscCall(PetscFree(is_general->idx));
 26:   PetscCall(PetscObjectComposeFunction((PetscObject)is, "ISGeneralSetIndices_C", NULL));
 27:   PetscCall(PetscObjectComposeFunction((PetscObject)is, "ISGeneralFilter_C", NULL));
 28:   PetscCall(PetscObjectComposeFunction((PetscObject)is, "ISGeneralSetIndicesFromMask_C", NULL));
 29:   PetscCall(PetscObjectComposeFunction((PetscObject)is, "ISShift_C", NULL));
 30:   PetscCall(PetscFree(is->data));
 31:   PetscFunctionReturn(PETSC_SUCCESS);
 32: }

 34: static PetscErrorCode ISCopy_General(IS is, IS isy)
 35: {
 36:   IS_General *is_general = (IS_General *)is->data, *isy_general = (IS_General *)isy->data;
 37:   PetscInt    n;

 39:   PetscFunctionBegin;
 40:   PetscCall(PetscLayoutGetLocalSize(is->map, &n));
 41:   PetscCall(PetscArraycpy(isy_general->idx, is_general->idx, n));
 42:   PetscFunctionReturn(PETSC_SUCCESS);
 43: }

 45: static PetscErrorCode ISShift_General(IS is, PetscInt shift, IS isy)
 46: {
 47:   IS_General *is_general = (IS_General *)is->data, *isy_general = (IS_General *)isy->data;
 48:   PetscInt    i, n;

 50:   PetscFunctionBegin;
 51:   PetscCall(PetscLayoutGetLocalSize(is->map, &n));
 52:   for (i = 0; i < n; i++) isy_general->idx[i] = is_general->idx[i] + shift;
 53:   PetscFunctionReturn(PETSC_SUCCESS);
 54: }

 56: static PetscErrorCode ISOnComm_General(IS is, MPI_Comm comm, PetscCopyMode mode, IS *newis)
 57: {
 58:   IS_General *sub = (IS_General *)is->data;
 59:   PetscInt    n;

 61:   PetscFunctionBegin;
 62:   PetscCheck(mode != PETSC_OWN_POINTER, comm, PETSC_ERR_ARG_WRONG, "Cannot use PETSC_OWN_POINTER");
 63:   PetscCall(PetscLayoutGetLocalSize(is->map, &n));
 64:   PetscCall(ISCreateGeneral(comm, n, sub->idx, mode, newis));
 65:   PetscFunctionReturn(PETSC_SUCCESS);
 66: }

 68: static PetscErrorCode ISSetBlockSize_General(IS is, PetscInt bs)
 69: {
 70:   PetscFunctionBegin;
 71:   PetscCall(PetscLayoutSetBlockSize(is->map, bs));
 72:   PetscFunctionReturn(PETSC_SUCCESS);
 73: }

 75: static PetscErrorCode ISContiguousLocal_General(IS is, PetscInt gstart, PetscInt gend, PetscInt *start, PetscBool *contig)
 76: {
 77:   IS_General *sub = (IS_General *)is->data;
 78:   PetscInt    n, i, p;

 80:   PetscFunctionBegin;
 81:   *start  = 0;
 82:   *contig = PETSC_TRUE;
 83:   PetscCall(PetscLayoutGetLocalSize(is->map, &n));
 84:   if (!n) PetscFunctionReturn(PETSC_SUCCESS);
 85:   p = sub->idx[0];
 86:   if (p < gstart) goto nomatch;
 87:   *start = p - gstart;
 88:   if (n > gend - p) goto nomatch;
 89:   for (i = 1; i < n; i++, p++) {
 90:     if (sub->idx[i] != p + 1) goto nomatch;
 91:   }
 92:   PetscFunctionReturn(PETSC_SUCCESS);
 93: nomatch:
 94:   *start  = -1;
 95:   *contig = PETSC_FALSE;
 96:   PetscFunctionReturn(PETSC_SUCCESS);
 97: }

 99: static PetscErrorCode ISLocate_General(IS is, PetscInt key, PetscInt *location)
100: {
101:   IS_General *sub = (IS_General *)is->data;
102:   PetscInt    numIdx, i;
103:   PetscBool   sorted;

105:   PetscFunctionBegin;
106:   PetscCall(PetscLayoutGetLocalSize(is->map, &numIdx));
107:   PetscCall(ISGetInfo(is, IS_SORTED, IS_LOCAL, PETSC_TRUE, &sorted));
108:   if (sorted) PetscCall(PetscFindInt(key, numIdx, sub->idx, location));
109:   else {
110:     const PetscInt *idx = sub->idx;

112:     *location = -1;
113:     for (i = 0; i < numIdx; i++) {
114:       if (idx[i] == key) {
115:         *location = i;
116:         PetscFunctionReturn(PETSC_SUCCESS);
117:       }
118:     }
119:   }
120:   PetscFunctionReturn(PETSC_SUCCESS);
121: }

123: static PetscErrorCode ISGetIndices_General(IS in, const PetscInt *idx[])
124: {
125:   IS_General *sub = (IS_General *)in->data;

127:   PetscFunctionBegin;
128:   *idx = sub->idx;
129:   PetscFunctionReturn(PETSC_SUCCESS);
130: }

132: static PetscErrorCode ISRestoreIndices_General(IS in, const PetscInt *idx[])
133: {
134:   IS_General *sub = (IS_General *)in->data;

136:   PetscFunctionBegin;
137:   /* F90Array1dCreate() inside ISRestoreArray() does not keep array when zero length array */
138:   PetscCheck(in->map->n <= 0 || *idx == sub->idx, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Must restore with value from ISGetIndices()");
139:   PetscFunctionReturn(PETSC_SUCCESS);
140: }

142: static PetscErrorCode ISInvertPermutation_General(IS is, PetscInt nlocal, IS *isout)
143: {
144:   IS_General     *sub = (IS_General *)is->data;
145:   PetscInt        i, *ii, n, nstart;
146:   const PetscInt *idx = sub->idx;
147:   PetscMPIInt     size;
148:   IS              istmp, nistmp;

150:   PetscFunctionBegin;
151:   PetscCall(PetscLayoutGetLocalSize(is->map, &n));
152:   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)is), &size));
153:   if (size == 1) {
154:     PetscCall(PetscMalloc1(n, &ii));
155:     for (i = 0; i < n; i++) ii[idx[i]] = i;
156:     PetscCall(ISCreateGeneral(PETSC_COMM_SELF, n, ii, PETSC_OWN_POINTER, isout));
157:     PetscCall(ISSetPermutation(*isout));
158:   } else {
159:     /* crude, nonscalable get entire IS on each processor */
160:     PetscCall(ISAllGather(is, &istmp));
161:     PetscCall(ISSetPermutation(istmp));
162:     PetscCall(ISInvertPermutation(istmp, PETSC_DECIDE, &nistmp));
163:     PetscCall(ISDestroy(&istmp));
164:     /* get the part we need */
165:     if (nlocal == PETSC_DECIDE) nlocal = n;
166:     PetscCallMPI(MPI_Scan(&nlocal, &nstart, 1, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)is)));
167:     if (PetscDefined(USE_DEBUG)) {
168:       PetscInt    N;
169:       PetscMPIInt rank;
170:       PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)is), &rank));
171:       PetscCall(PetscLayoutGetSize(is->map, &N));
172:       PetscCheck((rank != size - 1) || (nstart == N), PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "Sum of nlocal lengths %" PetscInt_FMT " != total IS length %" PetscInt_FMT, nstart, N);
173:     }
174:     nstart -= nlocal;
175:     PetscCall(ISGetIndices(nistmp, &idx));
176:     PetscCall(ISCreateGeneral(PetscObjectComm((PetscObject)is), nlocal, idx + nstart, PETSC_COPY_VALUES, isout));
177:     PetscCall(ISRestoreIndices(nistmp, &idx));
178:     PetscCall(ISDestroy(&nistmp));
179:   }
180:   PetscFunctionReturn(PETSC_SUCCESS);
181: }

183: /*
184:   FindRun_Private - Determine whether a run exists in the sequence

186:   Input Parameters;
187: + indices   - An array of indices
188: . len       - The length of `indices`
189: . off       - The offset into `indices`
190: - minRunLen - The minimum size of a run

192:   Output Parameters:
193: + runLen - The length of the run, with 0 meaning no run was found
194: . step   - The step between consecutive run values
195: - val    - The initial run value

197:   Note:
198:   We define a run as an arithmetic progression of at least `minRunLen` values, where zero is a valid step.
199: */
200: static PetscErrorCode ISFindRun_Private(const PetscInt indices[], PetscInt len, PetscInt off, PetscInt minRunLen, PetscInt *runLen, PetscInt *step, PetscInt *val)
201: {
202:   PetscInt o = off, s, l;

204:   PetscFunctionBegin;
205:   *runLen = 0;
206:   // We need at least 2 values for a run
207:   if (len - off < PetscMax(minRunLen, 2)) PetscFunctionReturn(PETSC_SUCCESS);
208:   s = indices[o + 1] - indices[o];
209:   l = 2;
210:   ++o;
211:   while (o < len - 1 && (s == indices[o + 1] - indices[o])) {
212:     ++l;
213:     ++o;
214:   }
215:   if (runLen) *runLen = l;
216:   if (step) *step = s;
217:   if (val) *val = indices[off];
218:   PetscFunctionReturn(PETSC_SUCCESS);
219: }

221: static PetscErrorCode ISGeneralCheckCompress(IS is, PetscBool *compress)
222: {
223:   const PetscInt  minRun    = 8;
224:   PetscBool       lcompress = PETSC_TRUE;
225:   const PetscInt *idx;
226:   PetscInt        n, off = 0;

228:   PetscFunctionBegin;
229:   *compress = PETSC_FALSE;
230:   if (!is->compressOutput) PetscFunctionReturn(PETSC_SUCCESS);
231:   PetscCall(ISGetIndices(is, &idx));
232:   PetscCall(ISGetLocalSize(is, &n));
233:   while (off < n) {
234:     PetscInt len;

236:     PetscCall(ISFindRun_Private(idx, n, off, minRun, &len, NULL, NULL));
237:     if (!len) {
238:       lcompress = PETSC_FALSE;
239:       break;
240:     }
241:     off += len;
242:   }
243:   PetscCallMPI(MPI_Allreduce(&lcompress, compress, 1, MPIU_BOOL, MPI_LAND, PetscObjectComm((PetscObject)is)));
244:   PetscFunctionReturn(PETSC_SUCCESS);
245: }

247: #if defined(PETSC_HAVE_HDF5)
248: // Run length encode the IS
249: static PetscErrorCode ISGeneralCompress(IS is, IS *cis)
250: {
251:   const PetscInt *idx;
252:   const PetscInt  minRun = 8;
253:   PetscInt        runs   = 0;
254:   PetscInt        off    = 0;
255:   PetscInt       *cidx, n, r;
256:   const char     *name;
257:   MPI_Comm        comm;

259:   PetscFunctionBegin;
260:   PetscCall(PetscObjectGetComm((PetscObject)is, &comm));
261:   PetscCall(ISGetIndices(is, &idx));
262:   PetscCall(ISGetLocalSize(is, &n));
263:   if (!n) runs = 0;
264:   // Count runs
265:   while (off < n) {
266:     PetscInt len;

268:     PetscCall(ISFindRun_Private(idx, n, off, minRun, &len, NULL, NULL));
269:     PetscCheck(len, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Compression failed to find a run at offset %" PetscInt_FMT, off);
270:     ++runs;
271:     off += len;
272:   }
273:   // Construct compressed set
274:   PetscCall(PetscMalloc1(runs * 3, &cidx));
275:   off = 0;
276:   r   = 0;
277:   while (off < n) {
278:     PetscCall(ISFindRun_Private(idx, n, off, minRun, &cidx[r * 3 + 0], &cidx[r * 3 + 1], &cidx[r * 3 + 2]));
279:     PetscCheck(cidx[r * 3 + 0], PETSC_COMM_SELF, PETSC_ERR_PLIB, "Compression failed to find a run at offset %" PetscInt_FMT, off);
280:     off += cidx[r * 3 + 0];
281:     ++r;
282:   }
283:   PetscCheck(r == runs, comm, PETSC_ERR_PLIB, "The number of runs %" PetscInt_FMT " != %" PetscInt_FMT " computed chunks", runs, r);
284:   PetscCheck(off == n, comm, PETSC_ERR_PLIB, "The local size %" PetscInt_FMT " != %" PetscInt_FMT " total encoded size", n, off);
285:   PetscCall(ISCreateGeneral(comm, runs * 3, cidx, PETSC_OWN_POINTER, cis));
286:   PetscCall(PetscLayoutSetBlockSize((*cis)->map, 3));
287:   PetscCall(PetscObjectGetName((PetscObject)is, &name));
288:   PetscCall(PetscObjectSetName((PetscObject)*cis, name));
289:   PetscFunctionReturn(PETSC_SUCCESS);
290: }

292: static PetscErrorCode ISView_General_HDF5(IS is, PetscViewer viewer)
293: {
294:   PetscViewer_HDF5 *hdf5 = (PetscViewer_HDF5 *)viewer->data;
295:   hid_t             filespace;  /* file dataspace identifier */
296:   hid_t             chunkspace; /* chunk dataset property identifier */
297:   hid_t             dset_id;    /* dataset identifier */
298:   hid_t             memspace;   /* memory dataspace identifier */
299:   hid_t             inttype;    /* int type (H5T_NATIVE_INT or H5T_NATIVE_LLONG) */
300:   hid_t             file_id, group;
301:   hsize_t           dim, maxDims[3], dims[3], chunkDims[3], count[3], offset[3];
302:   PetscBool         timestepping;
303:   PetscInt          bs, N, n, timestep = PETSC_INT_MIN, low;
304:   hsize_t           chunksize;
305:   const PetscInt   *ind;
306:   const char       *isname;

308:   PetscFunctionBegin;
309:   PetscCall(ISGetBlockSize(is, &bs));
310:   bs = PetscMax(bs, 1); /* If N = 0, bs  = 0 as well */
311:   PetscCall(PetscViewerHDF5OpenGroup(viewer, NULL, &file_id, &group));
312:   PetscCall(PetscViewerHDF5IsTimestepping(viewer, &timestepping));
313:   if (timestepping) PetscCall(PetscViewerHDF5GetTimestep(viewer, &timestep));

315:   /* Create the dataspace for the dataset.
316:    *
317:    * dims - holds the current dimensions of the dataset
318:    *
319:    * maxDims - holds the maximum dimensions of the dataset (unlimited
320:    * for the number of time steps with the current dimensions for the
321:    * other dimensions; so only additional time steps can be added).
322:    *
323:    * chunkDims - holds the size of a single time step (required to
324:    * permit extending dataset).
325:    */
326:   dim       = 0;
327:   chunksize = 1;
328:   if (timestep >= 0) {
329:     dims[dim]      = timestep + 1;
330:     maxDims[dim]   = H5S_UNLIMITED;
331:     chunkDims[dim] = 1;
332:     ++dim;
333:   }
334:   PetscCall(ISGetSize(is, &N));
335:   PetscCall(ISGetLocalSize(is, &n));
336:   PetscCall(PetscHDF5IntCast(N / bs, dims + dim));

338:   maxDims[dim]   = dims[dim];
339:   chunkDims[dim] = PetscMax(1, dims[dim]);
340:   chunksize *= chunkDims[dim];
341:   ++dim;
342:   if (bs >= 1) {
343:     dims[dim]      = bs;
344:     maxDims[dim]   = dims[dim];
345:     chunkDims[dim] = dims[dim];
346:     chunksize *= chunkDims[dim];
347:     ++dim;
348:   }
349:   /* hdf5 chunks must be less than 4GB */
350:   if (chunksize > PETSC_HDF5_MAX_CHUNKSIZE / 64) {
351:     if (bs >= 1) {
352:       if (chunkDims[dim - 2] > (hsize_t)PetscSqrtReal((PetscReal)(PETSC_HDF5_MAX_CHUNKSIZE / 64))) chunkDims[dim - 2] = (hsize_t)PetscSqrtReal((PetscReal)(PETSC_HDF5_MAX_CHUNKSIZE / 64));
353:       if (chunkDims[dim - 1] > (hsize_t)PetscSqrtReal((PetscReal)(PETSC_HDF5_MAX_CHUNKSIZE / 64))) chunkDims[dim - 1] = (hsize_t)PetscSqrtReal((PetscReal)(PETSC_HDF5_MAX_CHUNKSIZE / 64));
354:     } else {
355:       chunkDims[dim - 1] = PETSC_HDF5_MAX_CHUNKSIZE / 64;
356:     }
357:   }
358:   PetscCallHDF5Return(filespace, H5Screate_simple, ((int)dim, dims, maxDims));

360:   #if defined(PETSC_USE_64BIT_INDICES)
361:   inttype = H5T_NATIVE_LLONG;
362:   #else
363:   inttype = H5T_NATIVE_INT;
364:   #endif

366:   /* Create the dataset with default properties and close filespace */
367:   PetscCall(PetscObjectGetName((PetscObject)is, &isname));
368:   if (!H5Lexists(group, isname, H5P_DEFAULT)) {
369:     /* Create chunk */
370:     PetscCallHDF5Return(chunkspace, H5Pcreate, (H5P_DATASET_CREATE));
371:     PetscCallHDF5(H5Pset_chunk, (chunkspace, (int)dim, chunkDims));

373:     PetscCallHDF5Return(dset_id, H5Dcreate2, (group, isname, inttype, filespace, H5P_DEFAULT, chunkspace, H5P_DEFAULT));
374:     PetscCallHDF5(H5Pclose, (chunkspace));
375:   } else {
376:     PetscCallHDF5Return(dset_id, H5Dopen2, (group, isname, H5P_DEFAULT));
377:     PetscCallHDF5(H5Dset_extent, (dset_id, dims));
378:   }
379:   PetscCallHDF5(H5Sclose, (filespace));

381:   /* Each process defines a dataset and writes it to the hyperslab in the file */
382:   dim = 0;
383:   if (timestep >= 0) {
384:     count[dim] = 1;
385:     ++dim;
386:   }
387:   PetscCall(PetscHDF5IntCast(n / bs, count + dim));
388:   ++dim;
389:   if (bs >= 1) {
390:     count[dim] = bs;
391:     ++dim;
392:   }
393:   if (n > 0 || H5_VERSION_GE(1, 10, 0)) {
394:     PetscCallHDF5Return(memspace, H5Screate_simple, ((int)dim, count, NULL));
395:   } else {
396:     /* Can't create dataspace with zero for any dimension, so create null dataspace. */
397:     PetscCallHDF5Return(memspace, H5Screate, (H5S_NULL));
398:   }

400:   /* Select hyperslab in the file */
401:   PetscCall(PetscLayoutGetRange(is->map, &low, NULL));
402:   dim = 0;
403:   if (timestep >= 0) {
404:     offset[dim] = timestep;
405:     ++dim;
406:   }
407:   PetscCall(PetscHDF5IntCast(low / bs, offset + dim));
408:   ++dim;
409:   if (bs >= 1) {
410:     offset[dim] = 0;
411:     ++dim;
412:   }
413:   if (n > 0 || H5_VERSION_GE(1, 10, 0)) {
414:     PetscCallHDF5Return(filespace, H5Dget_space, (dset_id));
415:     PetscCallHDF5(H5Sselect_hyperslab, (filespace, H5S_SELECT_SET, offset, NULL, count, NULL));
416:   } else {
417:     /* Create null filespace to match null memspace. */
418:     PetscCallHDF5Return(filespace, H5Screate, (H5S_NULL));
419:   }

421:   PetscCall(ISGetIndices(is, &ind));
422:   PetscCallHDF5(H5Dwrite, (dset_id, inttype, memspace, filespace, hdf5->dxpl_id, ind));
423:   PetscCallHDF5(H5Fflush, (file_id, H5F_SCOPE_GLOBAL));
424:   PetscCall(ISRestoreIndices(is, &ind));

426:   /* Close/release resources */
427:   PetscCallHDF5(H5Gclose, (group));
428:   PetscCallHDF5(H5Sclose, (filespace));
429:   PetscCallHDF5(H5Sclose, (memspace));
430:   PetscCallHDF5(H5Dclose, (dset_id));

432:   if (timestepping) PetscCall(PetscViewerHDF5WriteObjectAttribute(viewer, (PetscObject)is, "timestepping", PETSC_BOOL, &timestepping));
433:   PetscCall(PetscInfo(is, "Wrote IS object with name %s\n", isname));
434:   PetscFunctionReturn(PETSC_SUCCESS);
435: }

437: static PetscErrorCode ISView_General_HDF5_Compressed(IS is, PetscViewer viewer)
438: {
439:   const PetscBool compressed = PETSC_TRUE;
440:   const char     *isname;
441:   IS              cis;
442:   PetscBool       timestepping;

444:   PetscFunctionBegin;
445:   PetscCall(PetscViewerHDF5IsTimestepping(viewer, &timestepping));
446:   PetscCheck(!timestepping, PetscObjectComm((PetscObject)viewer), PETSC_ERR_ARG_WRONG, "Timestepping not supported for compressed writing");

448:   PetscCall(ISGeneralCompress(is, &cis));
449:   PetscCall(ISView_General_HDF5(cis, viewer));
450:   PetscCall(PetscViewerHDF5WriteObjectAttribute(viewer, (PetscObject)cis, "compressed", PETSC_BOOL, &compressed));
451:   PetscCall(ISDestroy(&cis));

453:   PetscCall(PetscObjectGetName((PetscObject)is, &isname));
454:   PetscCall(PetscInfo(is, "Wrote compressed IS object with name %s\n", isname));
455:   PetscFunctionReturn(PETSC_SUCCESS);
456: }
457: #endif

459: static PetscErrorCode ISView_General(IS is, PetscViewer viewer)
460: {
461:   IS_General *sub = (IS_General *)is->data;
462:   PetscInt   *idx = sub->idx, n;
463:   PetscBool   iascii, isbinary, ishdf5, compress;

465:   PetscFunctionBegin;
466:   PetscCall(PetscLayoutGetLocalSize(is->map, &n));
467:   PetscCall(ISGeneralCheckCompress(is, &compress));
468:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
469:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
470:   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERHDF5, &ishdf5));
471:   if (iascii) {
472:     MPI_Comm          comm;
473:     PetscMPIInt       rank, size;
474:     PetscViewerFormat fmt;
475:     PetscBool         isperm;

477:     PetscCall(PetscObjectGetComm((PetscObject)viewer, &comm));
478:     PetscCallMPI(MPI_Comm_rank(comm, &rank));
479:     PetscCallMPI(MPI_Comm_size(comm, &size));

481:     PetscCall(PetscViewerGetFormat(viewer, &fmt));
482:     PetscCall(ISGetInfo(is, IS_PERMUTATION, IS_LOCAL, PETSC_FALSE, &isperm));
483:     if (isperm && fmt != PETSC_VIEWER_ASCII_MATLAB) PetscCall(PetscViewerASCIIPrintf(viewer, "Index set is permutation\n"));
484:     PetscCall(PetscViewerASCIIPushSynchronized(viewer));
485:     if (size > 1) {
486:       if (fmt == PETSC_VIEWER_ASCII_MATLAB) {
487:         const char *name;

489:         PetscCall(PetscObjectGetName((PetscObject)is, &name));
490:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%s_%d = [...\n", name, rank));
491:         for (PetscInt i = 0; i < n; i++) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%" PetscInt_FMT "\n", idx[i] + 1));
492:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "];\n"));
493:       } else {
494:         PetscInt st = 0;

496:         if (fmt == PETSC_VIEWER_ASCII_INDEX) st = is->map->rstart;
497:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] Number of indices in set %" PetscInt_FMT "\n", rank, n));
498:         for (PetscInt i = 0; i < n; i++) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] %" PetscInt_FMT " %" PetscInt_FMT "\n", rank, i + st, idx[i]));
499:       }
500:     } else {
501:       if (fmt == PETSC_VIEWER_ASCII_MATLAB) {
502:         const char *name;

504:         PetscCall(PetscObjectGetName((PetscObject)is, &name));
505:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%s = [...\n", name));
506:         for (PetscInt i = 0; i < n; i++) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%" PetscInt_FMT "\n", idx[i] + 1));
507:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "];\n"));
508:       } else {
509:         PetscInt st = 0;

511:         if (fmt == PETSC_VIEWER_ASCII_INDEX) st = is->map->rstart;
512:         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "Number of indices in set %" PetscInt_FMT "\n", n));
513:         for (PetscInt i = 0; i < n; i++) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%" PetscInt_FMT " %" PetscInt_FMT "\n", i + st, idx[i]));
514:       }
515:     }
516:     PetscCall(PetscViewerFlush(viewer));
517:     PetscCall(PetscViewerASCIIPopSynchronized(viewer));
518:   } else if (isbinary) {
519:     PetscCall(ISView_Binary(is, viewer));
520:   } else if (ishdf5) {
521: #if defined(PETSC_HAVE_HDF5)
522:     if (compress) PetscCall(ISView_General_HDF5_Compressed(is, viewer));
523:     else PetscCall(ISView_General_HDF5(is, viewer));
524: #endif
525:   }
526:   PetscFunctionReturn(PETSC_SUCCESS);
527: }

529: static PetscErrorCode ISSort_General(IS is)
530: {
531:   IS_General *sub = (IS_General *)is->data;
532:   PetscInt    n;

534:   PetscFunctionBegin;
535:   PetscCall(PetscLayoutGetLocalSize(is->map, &n));
536:   PetscCall(PetscIntSortSemiOrdered(n, sub->idx));
537:   PetscFunctionReturn(PETSC_SUCCESS);
538: }

540: static PetscErrorCode ISSortRemoveDups_General(IS is)
541: {
542:   IS_General *sub = (IS_General *)is->data;
543:   PetscLayout map;
544:   PetscInt    n;
545:   PetscBool   sorted;

547:   PetscFunctionBegin;
548:   PetscCall(PetscLayoutGetLocalSize(is->map, &n));
549:   PetscCall(ISGetInfo(is, IS_SORTED, IS_LOCAL, PETSC_TRUE, &sorted));
550:   if (sorted) {
551:     PetscCall(PetscSortedRemoveDupsInt(&n, sub->idx));
552:   } else {
553:     PetscCall(PetscSortRemoveDupsInt(&n, sub->idx));
554:   }
555:   PetscCall(PetscLayoutCreateFromSizes(PetscObjectComm((PetscObject)is), n, PETSC_DECIDE, is->map->bs, &map));
556:   PetscCall(PetscLayoutDestroy(&is->map));
557:   is->map = map;
558:   PetscFunctionReturn(PETSC_SUCCESS);
559: }

561: static PetscErrorCode ISSorted_General(IS is, PetscBool *flg)
562: {
563:   PetscFunctionBegin;
564:   PetscCall(ISGetInfo(is, IS_SORTED, IS_LOCAL, PETSC_TRUE, flg));
565:   PetscFunctionReturn(PETSC_SUCCESS);
566: }

568: static PetscErrorCode ISToGeneral_General(IS is)
569: {
570:   PetscFunctionBegin;
571:   PetscFunctionReturn(PETSC_SUCCESS);
572: }

574: // clang-format off
575: static const struct _ISOps myops = {
576:   PetscDesignatedInitializer(getindices, ISGetIndices_General),
577:   PetscDesignatedInitializer(restoreindices, ISRestoreIndices_General),
578:   PetscDesignatedInitializer(invertpermutation, ISInvertPermutation_General),
579:   PetscDesignatedInitializer(sort, ISSort_General),
580:   PetscDesignatedInitializer(sortremovedups, ISSortRemoveDups_General),
581:   PetscDesignatedInitializer(sorted, ISSorted_General),
582:   PetscDesignatedInitializer(duplicate, ISDuplicate_General),
583:   PetscDesignatedInitializer(destroy, ISDestroy_General),
584:   PetscDesignatedInitializer(view, ISView_General),
585:   PetscDesignatedInitializer(load, ISLoad_Default),
586:   PetscDesignatedInitializer(copy, ISCopy_General),
587:   PetscDesignatedInitializer(togeneral, ISToGeneral_General),
588:   PetscDesignatedInitializer(oncomm, ISOnComm_General),
589:   PetscDesignatedInitializer(setblocksize, ISSetBlockSize_General),
590:   PetscDesignatedInitializer(contiguous, ISContiguousLocal_General),
591:   PetscDesignatedInitializer(locate, ISLocate_General),
592:   /* no specializations of {sorted,unique,perm,interval}{local,global} because the default
593:    * checks in ISGetInfo_XXX in index.c are exactly what we would do for ISGeneral */
594:   PetscDesignatedInitializer(sortedlocal, NULL),
595:   PetscDesignatedInitializer(sortedglobal, NULL),
596:   PetscDesignatedInitializer(uniquelocal, NULL),
597:   PetscDesignatedInitializer(uniqueglobal, NULL),
598:   PetscDesignatedInitializer(permlocal, NULL),
599:   PetscDesignatedInitializer(permglobal, NULL),
600:   PetscDesignatedInitializer(intervallocal, NULL),
601:   PetscDesignatedInitializer(intervalglobal, NULL)
602: };
603: // clang-format on

605: PETSC_INTERN PetscErrorCode ISSetUp_General(IS is)
606: {
607:   IS_General     *sub = (IS_General *)is->data;
608:   const PetscInt *idx = sub->idx;
609:   PetscInt        n, i, min, max;

611:   PetscFunctionBegin;
612:   PetscCall(PetscLayoutGetLocalSize(is->map, &n));

614:   if (n) {
615:     min = max = idx[0];
616:     for (i = 1; i < n; i++) {
617:       if (idx[i] < min) min = idx[i];
618:       if (idx[i] > max) max = idx[i];
619:     }
620:     is->min = min;
621:     is->max = max;
622:   } else {
623:     is->min = PETSC_INT_MAX;
624:     is->max = PETSC_INT_MIN;
625:   }
626:   PetscFunctionReturn(PETSC_SUCCESS);
627: }

629: /*@
630:   ISCreateGeneral - Creates a data structure for an index set containing a list of integers.

632:   Collective

634:   Input Parameters:
635: + comm - the MPI communicator
636: . n    - the length of the index set
637: . idx  - the list of integers
638: - mode - `PETSC_COPY_VALUES`, `PETSC_OWN_POINTER`, or `PETSC_USE_POINTER`; see `PetscCopyMode` for meaning of this flag.

640:   Output Parameter:
641: . is - the new index set

643:   Level: beginner

645:   Notes:
646:   When the communicator is not `MPI_COMM_SELF`, the operations on IS are NOT
647:   conceptually the same as `MPI_Group` operations. The `IS` are then
648:   distributed sets of indices and thus certain operations on them are
649:   collective.

651:   Use `ISGeneralSetIndices()` to provide indices to an already existing `IS` of `ISType` `ISGENERAL`

653: .seealso: [](sec_scatter), `IS`, `ISGENERAL`, `ISCreateStride()`, `ISCreateBlock()`, `ISAllGather()`, `PETSC_COPY_VALUES`, `PETSC_OWN_POINTER`,
654:           `PETSC_USE_POINTER`, `PetscCopyMode`, `ISGeneralSetIndicesFromMask()`
655: @*/
656: PetscErrorCode ISCreateGeneral(MPI_Comm comm, PetscInt n, const PetscInt idx[], PetscCopyMode mode, IS *is)
657: {
658:   PetscFunctionBegin;
659:   PetscCall(ISCreate(comm, is));
660:   PetscCall(ISSetType(*is, ISGENERAL));
661:   PetscCall(ISGeneralSetIndices(*is, n, idx, mode));
662:   PetscFunctionReturn(PETSC_SUCCESS);
663: }

665: /*@
666:   ISGeneralSetIndices - Sets the indices for an `ISGENERAL` index set

668:   Logically Collective

670:   Input Parameters:
671: + is   - the index set
672: . n    - the length of the index set
673: . idx  - the list of integers
674: - mode - see `PetscCopyMode` for meaning of this flag.

676:   Level: beginner

678:   Note:
679:   Use `ISCreateGeneral()` to create the `IS` and set its indices in a single function call

681: .seealso: [](sec_scatter), `IS`, `ISBLOCK`, `ISCreateGeneral()`, `ISGeneralSetIndicesFromMask()`, `ISBlockSetIndices()`, `ISGENERAL`, `PetscCopyMode`
682: @*/
683: PetscErrorCode ISGeneralSetIndices(IS is, PetscInt n, const PetscInt idx[], PetscCopyMode mode)
684: {
685:   PetscFunctionBegin;
687:   PetscCheck(n >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "length < 0");
688:   if (n) PetscAssertPointer(idx, 3);
689:   PetscCall(ISClearInfoCache(is, PETSC_FALSE));
690:   PetscUseMethod(is, "ISGeneralSetIndices_C", (IS, PetscInt, const PetscInt[], PetscCopyMode), (is, n, idx, mode));
691:   PetscFunctionReturn(PETSC_SUCCESS);
692: }

694: static PetscErrorCode ISGeneralSetIndices_General(IS is, PetscInt n, const PetscInt idx[], PetscCopyMode mode)
695: {
696:   PetscLayout map;
697:   IS_General *sub = (IS_General *)is->data;

699:   PetscFunctionBegin;
700:   PetscCall(PetscLayoutCreateFromSizes(PetscObjectComm((PetscObject)is), n, PETSC_DECIDE, is->map->bs, &map));
701:   PetscCall(PetscLayoutDestroy(&is->map));
702:   is->map = map;

704:   if (sub->allocated) PetscCall(PetscFree(sub->idx));
705:   if (mode == PETSC_COPY_VALUES) {
706:     PetscCall(PetscMalloc1(n, &sub->idx));
707:     PetscCall(PetscArraycpy(sub->idx, idx, n));
708:     sub->allocated = PETSC_TRUE;
709:   } else if (mode == PETSC_OWN_POINTER) {
710:     sub->idx       = (PetscInt *)idx;
711:     sub->allocated = PETSC_TRUE;
712:   } else {
713:     sub->idx       = (PetscInt *)idx;
714:     sub->allocated = PETSC_FALSE;
715:   }

717:   PetscCall(ISSetUp_General(is));
718:   PetscCall(ISViewFromOptions(is, NULL, "-is_view"));
719:   PetscFunctionReturn(PETSC_SUCCESS);
720: }

722: /*@
723:   ISGeneralSetIndicesFromMask - Sets the indices for an `ISGENERAL` index set using a boolean mask

725:   Collective

727:   Input Parameters:
728: + is     - the index set
729: . rstart - the range start index (inclusive)
730: . rend   - the range end index (exclusive)
731: - mask   - the boolean mask array of length rend-rstart, indices will be set for each `PETSC_TRUE` value in the array

733:   Level: beginner

735:   Note:
736:   The mask array may be freed by the user after this call.

738:   Example:
739: .vb
740:    PetscBool mask[] = {PETSC_FALSE, PETSC_TRUE, PETSC_FALSE, PETSC_FALSE, PETSC_TRUE};
741:    ISGeneralSetIndicesFromMask(is,10,15,mask);
742: .ve
743:   will feed the `IS` with indices
744: .vb
745:   {11, 14}
746: .ve
747:   locally.

749: .seealso: [](sec_scatter), `IS`, `ISCreateGeneral()`, `ISGeneralSetIndices()`, `ISGENERAL`
750: @*/
751: PetscErrorCode ISGeneralSetIndicesFromMask(IS is, PetscInt rstart, PetscInt rend, const PetscBool mask[])
752: {
753:   PetscFunctionBegin;
755:   PetscCheck(rstart <= rend, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "rstart %" PetscInt_FMT " must be less than or equal to rend %" PetscInt_FMT, rstart, rend);
756:   if (rend - rstart) PetscAssertPointer(mask, 4);
757:   PetscCall(ISClearInfoCache(is, PETSC_FALSE));
758:   PetscUseMethod(is, "ISGeneralSetIndicesFromMask_C", (IS, PetscInt, PetscInt, const PetscBool[]), (is, rstart, rend, mask));
759:   PetscFunctionReturn(PETSC_SUCCESS);
760: }

762: static PetscErrorCode ISGeneralSetIndicesFromMask_General(IS is, PetscInt rstart, PetscInt rend, const PetscBool mask[])
763: {
764:   PetscInt  i, nidx;
765:   PetscInt *idx;

767:   PetscFunctionBegin;
768:   for (i = 0, nidx = 0; i < rend - rstart; i++)
769:     if (mask[i]) nidx++;
770:   PetscCall(PetscMalloc1(nidx, &idx));
771:   for (i = 0, nidx = 0; i < rend - rstart; i++) {
772:     if (mask[i]) {
773:       idx[nidx] = i + rstart;
774:       nidx++;
775:     }
776:   }
777:   PetscCall(ISGeneralSetIndices_General(is, nidx, idx, PETSC_OWN_POINTER));
778:   PetscFunctionReturn(PETSC_SUCCESS);
779: }

781: static PetscErrorCode ISGeneralFilter_General(IS is, PetscInt start, PetscInt end)
782: {
783:   IS_General *sub = (IS_General *)is->data;
784:   PetscInt   *idx = sub->idx, *idxnew;
785:   PetscInt    i, n = is->map->n, nnew = 0, o;

787:   PetscFunctionBegin;
788:   for (i = 0; i < n; ++i)
789:     if (idx[i] >= start && idx[i] < end) nnew++;
790:   PetscCall(PetscMalloc1(nnew, &idxnew));
791:   for (o = 0, i = 0; i < n; i++) {
792:     if (idx[i] >= start && idx[i] < end) idxnew[o++] = idx[i];
793:   }
794:   PetscCall(ISGeneralSetIndices_General(is, nnew, idxnew, PETSC_OWN_POINTER));
795:   PetscFunctionReturn(PETSC_SUCCESS);
796: }

798: /*@
799:   ISGeneralFilter - Remove all indices outside of [start, end) from an `ISGENERAL`

801:   Collective

803:   Input Parameters:
804: + is    - the index set
805: . start - the lowest index kept
806: - end   - one more than the highest index kept, `start` $\le$ `end`

808:   Level: beginner

810: .seealso: [](sec_scatter), `IS`, `ISGENERAL`, `ISCreateGeneral()`, `ISGeneralSetIndices()`
811: @*/
812: PetscErrorCode ISGeneralFilter(IS is, PetscInt start, PetscInt end)
813: {
814:   PetscFunctionBegin;
816:   PetscCheck(start <= end, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "start %" PetscInt_FMT " must be less than or equal to end %" PetscInt_FMT, start, end);
817:   PetscCall(ISClearInfoCache(is, PETSC_FALSE));
818:   PetscUseMethod(is, "ISGeneralFilter_C", (IS, PetscInt, PetscInt), (is, start, end));
819:   PetscFunctionReturn(PETSC_SUCCESS);
820: }

822: PETSC_INTERN PetscErrorCode ISCreate_General(IS is)
823: {
824:   IS_General *sub;

826:   PetscFunctionBegin;
827:   PetscCall(PetscNew(&sub));
828:   is->data   = (void *)sub;
829:   is->ops[0] = myops;
830:   PetscCall(PetscObjectComposeFunction((PetscObject)is, "ISGeneralSetIndices_C", ISGeneralSetIndices_General));
831:   PetscCall(PetscObjectComposeFunction((PetscObject)is, "ISGeneralSetIndicesFromMask_C", ISGeneralSetIndicesFromMask_General));
832:   PetscCall(PetscObjectComposeFunction((PetscObject)is, "ISGeneralFilter_C", ISGeneralFilter_General));
833:   PetscCall(PetscObjectComposeFunction((PetscObject)is, "ISShift_C", ISShift_General));
834:   PetscFunctionReturn(PETSC_SUCCESS);
835: }