8#ifndef ERROR_MSG_BUFFER_SIZE
9#define ERROR_MSG_BUFFER_SIZE 256
20 PetscReal n[4], sigma;
22 PetscFunctionBeginUser;
23 displacement->
x = displacement->
y = displacement->
z = 0.0;
24 if (diff_eff <= 1.0e-12) PetscFunctionReturn(0);
32 sigma = PetscSqrtReal(2.0 * diff_eff * simCtx->
dt);
33 displacement->
x = sigma * n[0];
34 displacement->
y = sigma * n[1];
35 displacement->
z = sigma * n[2];
36 PetscFunctionReturn(0);
45 PetscFunctionBeginUser;
63 PetscFunctionReturn(0);
73 DM swarm = user->
swarm;
75 PetscReal *pos = NULL;
76 PetscReal *vel = NULL;
77 PetscReal *diffusivity = NULL;
78 Cmpnts *diffusivitygradient = NULL;
79 PetscReal *psi = NULL;
80 PetscReal *weights = NULL;
81 PetscInt *cell = NULL;
82 PetscInt *status = NULL;
83 PetscInt64 *pid = NULL;
88 PetscFunctionBeginUser;
93 ierr = DMSwarmGetLocalSize(swarm, &nLocal); CHKERRQ(ierr);
97 PetscFunctionReturn(0);
113 for (p = 0; p < nLocal; p++) {
118 ierr =
UnpackSwarmFields(p, pid, weights, pos, cell, vel, status, diffusivity, diffusivitygradient, psi, &particle); CHKERRQ(ierr);
124 "(%.6e, %.6e, %.6e) -> (%.6e, %.6e, %.6e) | vel (%.6e, %.6e, %.6e) | diffusivity %.6e gradient (%.6e, %.6e, %.6e) | dt %.6e\n",
125 old_loc.
x, old_loc.
y, old_loc.
z, particle.
loc.
x, particle.
loc.
y, particle.
loc.
z,
131 ierr =
UpdateSwarmFields(p, &particle, pos, vel, weights, cell, status, diffusivity, diffusivitygradient, psi); CHKERRQ(ierr);
150 PetscFunctionReturn(0);
159 PetscInt *removedCountLocal,
160 PetscInt *removedCountGlobal,
161 PetscReal *removedScalarSumGlobal,
162 PetscInt *exitedCountGlobal,
163 PetscReal *exitedScalarSumGlobal)
166 DM swarm = user->
swarm;
167 PetscInt nLocalInitial;
168 PetscInt *status_p = NULL;
169 PetscInt64 *pid_p = NULL;
170 PetscReal *pos_p = NULL;
171 PetscReal *psi_p = NULL;
172 PetscBool *remove = NULL;
173 PetscReal local_psi[2] = {0.0, 0.0};
174 PetscReal global_psi[2] = {0.0, 0.0};
175 PetscInt local_count[2] = {0, 0};
176 PetscInt global_count[2] = {0, 0};
179 PetscFunctionBeginUser;
185 *removedCountLocal = 0;
186 if (removedCountGlobal) *removedCountGlobal = 0;
187 if (removedScalarSumGlobal) *removedScalarSumGlobal = 0.0;
188 if (exitedCountGlobal) *exitedCountGlobal = 0;
189 if (exitedScalarSumGlobal) *exitedScalarSumGlobal = 0.0;
191 ierr = DMSwarmGetLocalSize(swarm, &nLocalInitial); CHKERRQ(ierr);
195 if (nLocalInitial > 0) {
201 ierr = PetscMalloc1(nLocalInitial, &remove); CHKERRQ(ierr);
204 for (PetscInt p = nLocalInitial - 1; p >= 0; p--) {
205 remove[p] = (PetscBool)(status_p[p] ==
LOST || status_p[p] ==
EXITED);
207 const PetscInt kind = (status_p[p] ==
LOST) ? 0 : 1;
208 LOG_PARTICLE(user->
simCtx, pid_p[p],
"remove",
"%s at (%.6e, %.6e, %.6e) carrying psi %.6e: removed from rank %d\n",
210 pos_p[3*p], pos_p[3*p+1], pos_p[3*p+2], psi_p[p], (
int)rank);
212 local_psi[kind] += psi_p[p];
222 ierr = PetscFree(remove); CHKERRQ(ierr);
225 PetscInt nLocalFinal;
226 ierr = DMSwarmGetLocalSize(swarm, &nLocalFinal); CHKERRQ(ierr);
227 LOG_ALLOW(
LOCAL,
LOG_INFO,
"Rank %d: Finished removing %" PetscInt_FMT
" LOST and %" PetscInt_FMT
" EXITED particles. Final local size: %" PetscInt_FMT
".\n",
228 rank, local_count[0], local_count[1], nLocalFinal);
231 *removedCountLocal = local_count[0];
232 if (removedCountGlobal || exitedCountGlobal) {
233 ierr = MPI_Allreduce(local_count, global_count, 2, MPIU_INT, MPI_SUM, PetscObjectComm((PetscObject)swarm)); CHKERRMPI(ierr);
234 if (removedCountGlobal) *removedCountGlobal = global_count[0];
235 if (exitedCountGlobal) *exitedCountGlobal = global_count[1];
236 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Removed %" PetscInt_FMT
" LOST and %" PetscInt_FMT
" EXITED particles globally.\n", global_count[0], global_count[1]);
238 if (removedScalarSumGlobal || exitedScalarSumGlobal) {
239 ierr = MPI_Allreduce(local_psi, global_psi, 2, MPIU_REAL, MPI_SUM,
240 PetscObjectComm((PetscObject)swarm)); CHKERRMPI(ierr);
241 if (removedScalarSumGlobal) *removedScalarSumGlobal = global_psi[0];
242 if (exitedScalarSumGlobal) *exitedScalarSumGlobal = global_psi[1];
246 PetscFunctionReturn(0);
257 DM swarm = user->
swarm;
259 PetscInt *rankField = NULL;
261 PetscFunctionBeginUser;
268 for(p_idx = 0; p_idx < migrationCount; ++p_idx) {
269 rankField[migrationList[p_idx].
local_index] = migrationList[p_idx].target_rank;
275 PetscFunctionReturn(0);
287 PetscInt n_local, n_kept = n_scan;
289 PetscFunctionBeginUser;
291 ierr = DMSwarmGetLocalSize(swarm, &n_local); CHKERRQ(ierr);
295 for (PetscInt k = 0; k < n_scan; ++k) {
296 PetscInt p = scan_backward ? n_scan - 1 - k : k;
297 while (p < n_kept && remove[p]) {
300 ierr = DMSwarmCopyPoint(swarm, n_kept, p); CHKERRQ(ierr);
301 remove[p] = remove[n_kept];
307 for (PetscInt q = n_scan; n_kept < n_scan && q < n_local; ++q) {
308 ierr = DMSwarmCopyPoint(swarm, q, n_kept + q - n_scan); CHKERRQ(ierr);
310 ierr = DMSwarmSetLocalSizes(swarm, n_kept + n_local - n_scan, -1); CHKERRQ(ierr);
313 PetscFunctionReturn(0);
322 const PetscInt *order, PetscInt n,
size_t bytes)
324 for (PetscInt p = 0; p < n; ++p) memcpy(out + (
size_t)p * bytes, in + (
size_t)order[p] * bytes, bytes);
335 PetscInt n_local, lo[3] = {PETSC_MAX_INT, PETSC_MAX_INT, PETSC_MAX_INT}, hi[3] = {-1, -1, -1};
336 PetscInt *cells = NULL, *order = NULL, *key = NULL;
337 PetscInt64 extent[3], nbuckets, *start = NULL;
338 PetscBool sorted = PETSC_TRUE;
340 size_t max_bytes = 0;
342 PetscFunctionBeginUser;
344 PetscCall(DMSwarmGetLocalSize(swarm, &n_local));
350 for (PetscInt p = 0; p < n_local; ++p) {
351 const PetscInt *c = &cells[3 * p];
352 if (c[0] < 0 || c[1] < 0 || c[2] < 0)
continue;
353 for (
int d = 0; d < 3; ++d) { lo[d] = PetscMin(lo[d], c[d]); hi[d] = PetscMax(hi[d], c[d]); }
355 for (
int d = 0; d < 3; ++d) extent[d] = (hi[d] >= lo[d]) ? (PetscInt64)(hi[d] - lo[d] + 1) : 0;
356 nbuckets = extent[0] * extent[1] * extent[2] + 1;
357 PetscCall(PetscMalloc2(n_local, &key, n_local, &order));
358 PetscCall(PetscCalloc1(nbuckets + 1, &start));
359 for (PetscInt p = 0; p < n_local; ++p) {
360 const PetscInt *c = &cells[3 * p];
361 const PetscInt64 b = (c[0] < 0 || c[1] < 0 || c[2] < 0) ? nbuckets - 1
362 : ((PetscInt64)(c[2] - lo[2]) * extent[1] + (c[1] - lo[1])) * extent[0] + (c[0] - lo[0]);
363 key[p] = (PetscInt)b;
364 if (p > 0 && key[p] < key[p - 1]) sorted = PETSC_FALSE;
369 PetscCall(PetscFree(start));
370 PetscCall(PetscFree2(key, order));
372 PetscFunctionReturn(0);
376 for (PetscInt64 b = 0; b < nbuckets; ++b) start[b + 1] += start[b];
377 for (PetscInt p = 0; p < n_local; ++p) order[start[key[p]]++] = p;
378 PetscCall(PetscFree(start));
387 PetscCall(PetscDataTypeGetSize(type, &type_bytes));
388 max_bytes = PetscMax(max_bytes, (
size_t)bs * type_bytes);
391 PetscCall(PetscMalloc1((
size_t)n_local * max_bytes, &buffer));
395 size_t type_bytes, bytes;
398 PetscCall(PetscDataTypeGetSize(type, &type_bytes));
399 bytes = (size_t)bs * type_bytes;
409 memcpy(data, buffer, (
size_t)n_local * bytes);
412 PetscCall(PetscFree(buffer));
413 PetscCall(PetscFree2(key, order));
415 PetscFunctionReturn(0);
428 DM swarm = user->
swarm;
430 PetscInt nlocal_before;
431 PetscInt *rank_p = NULL;
432 PetscBool *sent = NULL;
434 PetscFunctionBeginUser;
438 ierr = DMSwarmGetLocalSize(swarm, &nlocal_before); CHKERRQ(ierr);
443 ierr = DMSwarmMigrate(swarm, PETSC_FALSE); CHKERRQ(ierr);
446 ierr = PetscMalloc1(nlocal_before, &sent); CHKERRQ(ierr);
449 for (PetscInt p = 0; p < nlocal_before; ++p) {
450 sent[p] = (PetscBool)(rank_p[p] != rank);
451 if (sent[p]) n_sent++;
453 if (n_survivors) *n_survivors = nlocal_before - n_sent;
456 ierr = PetscFree(sent); CHKERRQ(ierr);
460 PetscFunctionReturn(0);
476 DM swarm = user->
swarm;
480 PetscInt *global_cell_id_arr;
481 PetscScalar ***count_arr_3d;
485 PetscInt particles_counted_locally = 0;
487 PetscFunctionBeginUser;
492 if (!da) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
"UserCtx->da is NULL.");
493 if (!swarm) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
"UserCtx->swarm is NULL.");
494 if (!countVec) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
"UserCtx->ParticleCount is NULL.");
497 count_dof = user->
info.dof;
498 if (count_dof != 1) {
499 PetscSNPrintf(msg,
sizeof(msg),
"countDM must have DOF=1, got %" PetscInt_FMT
".", count_dof);
500 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG,
"%s", msg);
504 ierr = VecSet(localcountVec, 0.0); CHKERRQ(ierr);
508 ierr = DMSwarmGetLocalSize(swarm, &nlocal); CHKERRQ(ierr);
514 ierr = DMDAVecGetArray(da, localcountVec, &count_arr_3d); CHKERRQ(ierr);
517 PetscInt gxs, gys, gzs, gxm, gym, gzm;
518 gxs = user->
info.gxs; gys = user->
info.gys; gzs = user->
info.gzs;
519 gxm = user->
info.gxm; gym = user->
info.gym; gzm = user->
info.gzm;
522 LOG_ALLOW(
LOCAL,
LOG_DEBUG,
"CalculateParticleCountPerCell (Rank %d): Processing %" PetscInt_FMT
" local particles using GLOBAL CellIDs.\n",rank,nlocal);
523 for (p = 0; p < nlocal; p++) {
525 PetscInt i_geom = global_cell_id_arr[p * 3 + 0];
526 PetscInt j_geom = global_cell_id_arr[p * 3 + 1];
527 PetscInt k_geom = global_cell_id_arr[p * 3 + 2];
530 PetscInt i = (PetscInt)i_geom + 1;
531 PetscInt j = (PetscInt)j_geom + 1;
532 PetscInt k = (PetscInt)k_geom + 1;
540 "[Rank %d] Read CellID for p=%" PetscInt_FMT
", PID = %" PetscInt64_FMT
": (%" PetscInt_FMT
", %" PetscInt_FMT
", %" PetscInt_FMT
")\n",
541 rank, p, PID_arr[p], i, j, k);
544 if (i >= gxs && i < gxs + gxm &&
545 j >= gys && j < gys + gym &&
546 k >= gzs && k < gzs + gzm )
551 count_arr_3d[k][j][i] += 1.0;
552 particles_counted_locally++;
557 "(Rank %d): Skipping particle %" PetscInt64_FMT
" with global CellID (%" PetscInt_FMT
", %" PetscInt_FMT
", %" PetscInt_FMT
") - likely outside local+ghost range.\n",
558 rank, PID_arr[p], i, j, k);
561 LOG_ALLOW(
LOCAL,
LOG_DEBUG,
"(Rank %d): Local counting finished. Processed %" PetscInt_FMT
" particles locally.\n", rank, particles_counted_locally);
564 ierr = DMDAVecRestoreArray(da, localcountVec, &count_arr_3d); CHKERRQ(ierr);
570 ierr = VecZeroEntries(countVec); CHKERRQ(ierr);
571 ierr = DMLocalToGlobalBegin(da, localcountVec, ADD_VALUES, countVec); CHKERRQ(ierr);
572 ierr = DMLocalToGlobalEnd(da, localcountVec, ADD_VALUES, countVec); CHKERRQ(ierr);
579 PetscReal total_counted_particles = 0.0, max_count_in_cell = 0.0;
580 ierr = VecSum(countVec, &total_counted_particles); CHKERRQ(ierr);
581 ierr = VecMax(countVec, NULL, &max_count_in_cell); CHKERRQ(ierr);
583 total_counted_particles, max_count_in_cell);
590 PetscFunctionReturn(0);
605 PetscInt N_current, N_final, nlocal_current, nlocal_target;
606 PetscMPIInt rank, size;
609 PetscFunctionBeginUser;
611 ierr = PetscObjectGetComm((PetscObject)swarm, &comm); CHKERRQ(ierr);
612 ierr = MPI_Comm_rank(comm, &rank); CHKERRQ(ierr);
613 ierr = MPI_Comm_size(comm, &size); CHKERRQ(ierr);
614 PetscCheck(N_target >= 0, comm, PETSC_ERR_ARG_OUTOFRANGE,
615 "Target swarm size must be nonnegative; got %" PetscInt_FMT
".", N_target);
616 ierr = DMSwarmGetSize(swarm, &N_current); CHKERRQ(ierr);
617 ierr = DMSwarmGetLocalSize(swarm, &nlocal_current); CHKERRQ(ierr);
618 nlocal_target = N_target / size + (rank < N_target % size ? 1 : 0);
620 if (nlocal_current != nlocal_target) {
622 "Rank %d: resizing local swarm share from %" PetscInt_FMT
623 " to %" PetscInt_FMT
".\n",
624 rank, nlocal_current, nlocal_target);
625 ierr = DMSwarmSetLocalSizes(swarm, nlocal_target, -1); CHKERRQ(ierr);
629 ierr = DMSwarmGetSize(swarm, &N_final); CHKERRQ(ierr);
630 if (N_final != N_target) {
631 SETERRQ(comm, PETSC_ERR_PLIB,
632 "Failed to resize swarm: expected %" PetscInt_FMT
633 " particles, got %" PetscInt_FMT, N_target, N_final);
636 "Swarm resized from %" PetscInt_FMT
" to %" PetscInt_FMT
" particles.\n",
639 PetscFunctionReturn(0);
652 PetscInt N_current = 0;
654 PetscFunctionBeginUser;
659 "Committed checkpoint step %" PetscInt_FMT
" records %" PetscInt_FMT
" particles.\n", ti, N_file);
663 ierr = DMSwarmGetSize(user->
swarm, &N_current); CHKERRQ(ierr);
665 if (N_file != N_current) {
666 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Swarm size %" PetscInt_FMT
" differs from file size %" PetscInt_FMT
". Resizing swarm globally.\n", N_current, N_file);
669 LOG_ALLOW(
GLOBAL,
LOG_DEBUG,
"Swarm size (%" PetscInt_FMT
") already matches file size. No resize needed.\n", N_current);
676 PetscFunctionReturn(0);
686 PetscInt64 **pids_snapshot_out)
691 PetscFunctionBeginUser;
696 if (!pids_snapshot_out) {
697 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
"Output pointer pids_snapshot_out is NULL.");
700 if (n_local > 0 && !pid_field) {
701 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
"Input pid_field pointer is NULL for n_local > 0.");
704 rank = PetscGlobalRank;
705 LOG_ALLOW(
LOCAL,
LOG_DEBUG,
"[Rank %d]: Creating PID snapshot for %" PetscInt_FMT
" local particles.\n", rank, n_local);
709 *pids_snapshot_out = NULL;
712 PetscFunctionReturn(0);
716 ierr = PetscMalloc1(n_local, pids_snapshot_out); CHKERRQ(ierr);
720 ierr = PetscMemcpy(*pids_snapshot_out, pid_field, n_local *
sizeof(PetscInt64)); CHKERRQ(ierr);
725 ierr = PetscSortInt64(n_local, *pids_snapshot_out); CHKERRQ(ierr);
730 PetscFunctionReturn(0);
738 PetscInt *capacity_p,
740 PetscInt particle_local_idx,
741 PetscMPIInt destination_rank)
746 PetscFunctionBeginUser;
751 if (!migration_list_p || !capacity_p || !count_p) {
752 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
"Null pointer provided to AddToMigrationList for list management.");
756 if (*count_p >= *capacity_p) {
757 PetscInt old_capacity = *capacity_p;
759 PetscInt new_capacity = (old_capacity == 0) ? 16 : old_capacity * 2;
764 ierr = PetscRealloc(new_capacity *
sizeof(
MigrationInfo), migration_list_p); CHKERRQ(ierr);
766 *capacity_p = new_capacity;
768 rank = PetscGlobalRank;
769 LOG_ALLOW(
LOCAL,
LOG_DEBUG,
"[Rank %d]: Reallocated migrationList capacity from %" PetscInt_FMT
" to %" PetscInt_FMT
".\n",
770 rank, old_capacity, new_capacity);
777 list[*count_p].local_index = particle_local_idx;
778 list[*count_p].target_rank = destination_rank;
785 PetscFunctionReturn(0);
801 PetscInt first_newcomer)
803 PetscInt n_after, mismatches = 0;
804 PetscInt64 *pid = NULL;
806 PetscFunctionBeginUser;
809 PetscCall(DMSwarmGetLocalSize(user->
swarm, &n_after));
811 for (PetscInt p = 0; p < n_after; ++p) {
812 PetscBool was_here = PETSC_FALSE;
813 if (n_before > 0) PetscCall(
BinarySearchInt64(n_before, pids_before, pid[p], &was_here));
814 if ((PetscBool)(p >= first_newcomer) == was_here) mismatches++;
817 PetscCheck(mismatches == 0, PETSC_COMM_SELF, PETSC_ERR_PLIB,
818 "Newcomer verification failed: %" PetscInt_FMT
" of %" PetscInt_FMT
" local particles disagree between position (first newcomer %" PetscInt_FMT
") and PID snapshot.",
819 mismatches, n_after, first_newcomer);
821 PetscFunctionReturn(0);
831 PetscInt n_local_after;
832 PetscInt *status = NULL;
834 PetscFunctionBeginUser;
836 PetscCheck(swarm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
"Input DMSwarm is NULL in FlagNewcomersForLocation.");
837 rank = PetscGlobalRank;
838 PetscCall(DMSwarmGetLocalSize(swarm, &n_local_after));
839 LOG_ALLOW(
LOCAL,
LOG_DEBUG,
"[Rank %d]: Checking for newcomers. Size before: %" PetscInt_FMT
", Size after: %" PetscInt_FMT
"\n",
840 rank, n_local_before, n_local_after);
841 PetscCheck(first_newcomer >= 0 && first_newcomer <= n_local_after, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
842 "First newcomer index %" PetscInt_FMT
" outside the %" PetscInt_FMT
" local particles.", first_newcomer, n_local_after);
845 for (PetscInt p = first_newcomer; p < n_local_after; ++p) {
849 if (n_local_after > first_newcomer) {
850 LOG_ALLOW(
LOCAL,
LOG_DEBUG,
"[Rank %d]: Identified and flagged %" PetscInt_FMT
" newcomers.\n", rank, n_local_after - first_newcomer);
853 PetscFunctionReturn(0);
863 DM swarm = user->
swarm;
865 PetscInt *cell_p = NULL;
866 PetscInt64 *pid_p = NULL;
870 PetscInt local_migration_count = 0;
871 PetscInt migrationListCapacity = 0;
872 PetscInt global_migration_count = 0;
874 PetscFunctionBeginUser;
878 ierr = DMSwarmGetLocalSize(swarm, &nlocal); CHKERRQ(ierr);
879 LOG_ALLOW(
LOCAL,
LOG_DEBUG,
"Checking %" PetscInt_FMT
" restart particles for direct migration using CellIDs.\n", nlocal);
888 for (PetscInt p_idx = 0; p_idx < nlocal; ++p_idx) {
889 PetscInt ci = cell_p[3*p_idx + 0];
890 PetscInt cj = cell_p[3*p_idx + 1];
891 PetscInt ck = cell_p[3*p_idx + 2];
894 if (ci < 0 || cj < 0 || ck < 0) {
898 PetscMPIInt owner_rank;
901 if (owner_rank != -1 && owner_rank != rank) {
903 ierr =
AddToMigrationList(&migrationList, &migrationListCapacity, &local_migration_count,
904 p_idx, owner_rank); CHKERRQ(ierr);
906 LOG_PARTICLE(user->
simCtx, pid_p[p_idx],
"restart",
"saved cell (%" PetscInt_FMT
",%" PetscInt_FMT
",%" PetscInt_FMT
") belongs to rank %d: migrating from rank %d\n",
907 ci, cj, ck, owner_rank, (
int)rank);
916 ierr = MPI_Allreduce(&local_migration_count, &global_migration_count, 1, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
918 if (global_migration_count > 0) {
919 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Fast restart migration: Directly migrating %" PetscInt_FMT
" particles using CellIDs.\n", global_migration_count);
920 ierr =
SetMigrationRanks(user, migrationList, local_migration_count); CHKERRQ(ierr);
928 ierr = PetscFree(migrationList); CHKERRQ(ierr);
931 PetscFunctionReturn(0);
950 PetscMPIInt *guess_rank_out)
952 PetscMPIInt rank, size;
953 const PetscMPIInt *neighbor;
956 PetscFunctionBeginUser;
960 if (!user || !particle || !guess_rank_out || !bboxlist) {
961 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
"Null pointer provided to GuessParticleOwnerWithBBox.");
964 localBBox = &user->
bbox;
968 *guess_rank_out = MPI_PROC_NULL;
973 *guess_rank_out = rank;
975 PetscFunctionReturn(0);
984 for (PetscInt d = 0; d < 3; ++d) step[d] = high[d] ? 1 : (low[d] ? -1 : 0);
986 if (across != MPI_PROC_NULL && across != rank &&
IsParticleInBox(&bboxlist[across], &particle->
loc)) {
987 *guess_rank_out = across;
989 PetscFunctionReturn(0);
995 for (PetscInt d = 0; d < 3; ++d) {
996 for (PetscInt side = -1; side <= 1; side += 2) {
997 PetscInt offset[3] = {0, 0, 0};
998 if (!((side < 0) ? low[d] : high[d]))
continue;
1001 if (face != MPI_PROC_NULL && face != across &&
IsParticleInBox(&bboxlist[face], &particle->
loc)) {
1002 *guess_rank_out = face;
1004 PetscFunctionReturn(0);
1010 for (PetscMPIInt r = 0; r < size; ++r) {
1011 if (r == rank)
continue;
1013 *guess_rank_out = r;
1015 PetscFunctionReturn(0);
1021 PetscFunctionReturn(0);
1032 PetscErrorCode ierr;
1033 PetscInt passes = 0;
1034 const PetscInt MAX_MIGRATION_PASSES = 50;
1035 PetscInt global_migrations_this_pass;
1037 PetscInt total_migrated_this_timestep = 0;
1039 PetscFunctionBeginUser;
1043 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"LocateAllParticlesInGrid (Orchestrator) - Beginning particle settlement process.\n");
1054 PetscInt local_migration_count = 0;
1055 PetscInt migrationListCapacity = 0;
1056 PetscInt nlocal_before;
1057 PetscInt64 *pids_before_snapshot = NULL;
1058 PetscInt local_lost_count = 0;
1060 ierr = DMSwarmGetLocalSize(user->
swarm, &nlocal_before); CHKERRQ(ierr);
1064 LOG_ALLOW(
LOCAL,
LOG_DEBUG,
"[Rank %d] Pass %" PetscInt_FMT
" begins with %" PetscInt_FMT
" local particles.\n", rank, passes, nlocal_before);
1068 if (nlocal_before > 0) {
1070 PetscReal *pos_p, *weights_p, *vel_p;
1071 PetscInt *cell_p, *status_p;
1089 for (PetscInt p_idx = 0; p_idx < nlocal_before; p_idx++) {
1094 (passes > 1 && (status_p[p_idx] ==
LOST || status_p[p_idx] ==
EXITED))) {
1100 ierr =
UnpackSwarmFields(p_idx, pid_p, weights_p, pos_p, cell_p, vel_p, status_p,NULL,NULL,NULL,¤t_particle); CHKERRQ(ierr);
1103 const PetscBool walk_from_prior_cell = (PetscBool)(current_particle.
cell[0] >= 0);
1107 if (walk_from_prior_cell) {
1114 PetscMPIInt guessed_owner_rank = MPI_PROC_NULL;
1118 if (guessed_owner_rank != MPI_PROC_NULL && guessed_owner_rank != rank) {
1120 LOG_PARTICLE(user->
simCtx, current_particle.
PID,
"locate",
"pass %" PetscInt_FMT
": bounding box of rank %d holds (%.6e, %.6e, %.6e): migrating there unwalked\n",
1121 passes, guessed_owner_rank, current_particle.
loc.
x, current_particle.
loc.
y, current_particle.
loc.
z);
1127 LOG_PARTICLE(user->
simCtx, current_particle.
PID,
"locate",
"pass %" PetscInt_FMT
": bounding-box guess %s; walking\n",
1128 passes, (guessed_owner_rank == rank) ?
"found this rank" :
"found no rank");
1135 ierr =
UpdateSwarmFields(p_idx, ¤t_particle, pos_p, vel_p, weights_p, cell_p, status_p,NULL,NULL,NULL); CHKERRQ(ierr);
1139 }
else if (final_status ==
LOST) {
1142 }
else if (final_status ==
EXITED) {
1161 LOG_ALLOW(
LOCAL,
LOG_DEBUG,
"[Rank %d] Pass %" PetscInt_FMT
": Identified %" PetscInt_FMT
" particles to migrate out.\n", rank, passes, local_migration_count);
1166 ierr = MPI_Allreduce(&local_migration_count, &global_migrations_this_pass, 1, MPIU_INT, MPI_SUM, PETSC_COMM_WORLD); CHKERRQ(ierr);
1168 total_migrated_this_timestep += global_migrations_this_pass;
1170 if(global_migrations_this_pass > 0 ){
1172 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"Pass %" PetscInt_FMT
": Migrating %" PetscInt_FMT
" particles globally.\n", passes, global_migrations_this_pass);
1174 ierr =
SetMigrationRanks(user, migrationList, local_migration_count); CHKERRQ(ierr);
1175 PetscInt n_survivors = 0;
1186 ierr = PetscFree(pids_before_snapshot);
1187 ierr = PetscFree(migrationList);
1189 LOG_ALLOW(
GLOBAL,
LOG_INFO,
"End of pass %" PetscInt_FMT
". Total particles migrated globally: %" PetscInt_FMT
".\n", passes, global_migrations_this_pass);
1191 }
while (global_migrations_this_pass > 0 && passes < MAX_MIGRATION_PASSES);
1194 if (passes >= MAX_MIGRATION_PASSES) {
1195 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_CONV_FAILED,
"Particle migration failed to converge after %" PetscInt_FMT
" passes. Check for particles oscillating between ranks.", MAX_MIGRATION_PASSES);
1206 PetscFunctionReturn(0);
1218 PetscErrorCode ierr;
1222 PetscFunctionBeginUser;
1226 ierr = DMSwarmGetLocalSize(user->
swarm, &n_local); CHKERRQ(ierr);
1232 for (PetscInt p = 0; p < n_local; ++p) {
1246 PetscFunctionReturn(0);
PetscErrorCode MetricRestoreFacePlaneArrays(UserCtx *user, FacePlaneArrays *arrays)
Closes arrays opened by MetricGetFacePlaneArrays().
PetscErrorCode MetricGetFacePlaneArrays(UserCtx *user, PetscBool dual, FacePlaneArrays *arrays)
Opens a family's face-plane arrays for reading; MetricComputeFacePlanes() must have run.
Read-only flat arrays of one family of face planes (grid cells or dual cells).
Configured initial values of particle-carried fields.
static PetscErrorCode VerifyNewcomersAgainstPIDs(UserCtx *user, PetscInt n_before, const PetscInt64 pids_before[], PetscInt first_newcomer)
Requires the position-identified newcomers to be exactly the PID-identified ones, when -picurv_verify...
PetscErrorCode SortParticlesByCell(DM swarm)
Implementation of SortParticlesByCell().
PetscErrorCode ResizeSwarmGlobally(DM swarm, PetscInt N_target)
Implementation of ResizeSwarmGlobally().
PetscErrorCode AddToMigrationList(MigrationInfo **migration_list_p, PetscInt *capacity_p, PetscInt *count_p, PetscInt particle_local_idx, PetscMPIInt destination_rank)
Implementation of AddToMigrationList().
PetscErrorCode SetMigrationRanks(UserCtx *user, const MigrationInfo *migrationList, PetscInt migrationCount)
Implementation of SetMigrationRanks().
PetscErrorCode RemoveFlaggedParticles(DM swarm, PetscInt n_scan, PetscBool remove[], PetscBool scan_backward)
Implementation of RemoveFlaggedParticles().
PetscErrorCode GetLocalPIDSnapshot(const PetscInt64 pid_field[], PetscInt n_local, PetscInt64 **pids_snapshot_out)
Implementation of GetLocalPIDSnapshot().
PetscErrorCode PerformMigration(UserCtx *user, PetscInt *n_survivors)
Implementation of PerformMigration().
PetscErrorCode MigrateRestartParticlesUsingCellID(UserCtx *user)
Implementation of MigrateRestartParticlesUsingCellID().
PetscErrorCode UpdateAllParticlePositions(UserCtx *user)
Implementation of UpdateAllParticlePositions().
PetscErrorCode CalculateParticleCountPerCell(UserCtx *user)
Implementation of CalculateParticleCountPerCell().
static PICURV_ALWAYS_INLINE void GatherSwarmRecords(char *out, const char *in, const PetscInt *order, PetscInt n, size_t bytes)
Copies n fixed-size records into out in the order order[] gives (out[p] = in[order[p]]).
PetscErrorCode LocateAllParticlesInGrid(UserCtx *user, BoundingBox *bboxlist)
Implementation of LocateAllParticlesInGrid().
PetscErrorCode CheckAndRemoveLostParticles(UserCtx *user, PetscInt *removedCountLocal, PetscInt *removedCountGlobal, PetscReal *removedScalarSumGlobal, PetscInt *exitedCountGlobal, PetscReal *exitedScalarSumGlobal)
Implementation of CheckAndRemoveLostParticles().
static PetscErrorCode GuessParticleOwnerWithBBox(UserCtx *user, const Particle *particle, const BoundingBox *bboxlist, PetscMPIInt *guess_rank_out)
Select the rank whose gathered bounding box is the best owner candidate for a particle.
#define ERROR_MSG_BUFFER_SIZE
PetscErrorCode UpdateParticlePosition(UserCtx *user, Particle *particle)
Implementation of UpdateParticlePosition().
PetscErrorCode ResetAllParticleStatuses(UserCtx *user)
Implementation of ResetAllParticleStatuses().
PetscErrorCode FlagNewcomersForLocation(DM swarm, PetscInt n_local_before, PetscInt first_newcomer)
Implementation of FlagNewcomersForLocation().
PetscErrorCode PreCheckAndResizeSwarm(UserCtx *user, PetscInt ti, const char *ext)
Implementation of PreCheckAndResizeSwarm().
PetscErrorCode CalculateBrownianDisplacement(UserCtx *user, PetscInt64 pid, PetscReal diff_eff, Cmpnts *displacement)
Implementation of CalculateBrownianDisplacement().
Header file for Particle Motion and migration related functions.
static PetscBool IsParticleInBox(const BoundingBox *bbox, const Cmpnts *pos)
Whether a position lies in an axis-aligned bounding box, faces included.
PetscErrorCode UnpackSwarmFields(PetscInt i, const PetscInt64 *PIDs, const PetscReal *weights, const PetscReal *positions, const PetscInt *cellIndices, PetscReal *velocities, PetscInt *LocStatus, PetscReal *diffusivity, Cmpnts *diffusivitygradient, PetscReal *psi, Particle *particle)
Initializes a Particle struct with data from DMSwarm fields.
PetscErrorCode UpdateSwarmFields(PetscInt i, const Particle *particle, PetscReal *positions, PetscReal *velocities, PetscReal *weights, PetscInt *cellIndices, PetscInt *status, PetscReal *diffusivity, Cmpnts *diffusivitygradient, PetscReal *psi)
Updates DMSwarm data arrays from a Particle struct.
uint64_t PicurvMix64(uint64_t z)
splitmix64 finalizer: a bijective mix of 64 bits.
uint64_t PicurvDrawHash(PetscInt64 seed, PicurvDrawSpace space, uint64_t stream, PetscInt64 id, PetscInt64 salt)
Hash that keys a draw: a pure function of its arguments, so a draw does not depend on the rank that m...
void PicurvNormalPairFromHash(uint64_t hash, PetscReal normal[2])
Two independent standard normal deviates from a hash, by Box-Muller from two uniforms it yields.
@ PICURV_DRAW_SPACE_BROWNIAN
Brownian increments; the salt is the step.
PetscErrorCode ReadCheckpointParticleCount(UserCtx *user, PetscInt ti, PetscInt *particle_count)
Read the particle count from a validated committed checkpoint.
#define LOG_PARTICLE(simCtx, pid, stage, fmt,...)
Reports one particle at one stage of a step: the consolidated per-particle line.
#define LOG_LOOP_ALLOW(scope, level, iterVar, interval, fmt,...)
Logs a message inside a loop, but only every interval iterations.
#define LOCAL
Logging scope definitions for controlling message output.
#define GLOBAL
Scope for global logging across all processes.
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
#define PROFILE_HELPER_BEGIN
Marks the beginning of a profiled helper: timed only when enabled by name.
#define PROFILE_HELPER_END
Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
const char * ParticleLocationStatusToString(ParticleLocationStatus level)
A function that outputs the name of the current level in the ParticleLocation enum.
@ LOG_INFO
Informational messages about program execution.
@ LOG_DEBUG
Detailed debugging information.
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
PetscErrorCode ResetSearchMetrics(SimCtx *simCtx)
Resets the aggregate per-timestep search instrumentation counters.
#define LOG_LEVEL_ADMITS(level)
True when a code-level diagnostic at level prints from the calling function.
Typed identities and metadata for persistent solver-particle fields.
const char * ParticleFieldName(ParticleFieldId field_id)
Return the canonical PETSc DMSwarm name for an ID.
ParticleFieldId
Compile-time identity for a persistent solver-particle field.
@ PARTICLE_FIELD_ID_LOCATION_STATUS
@ PARTICLE_FIELD_ID_WEIGHT
@ PARTICLE_FIELD_ID_POSITION
@ PARTICLE_FIELD_ID_CELL_ID
@ PARTICLE_FIELD_ID_DIFFUSIVITY_GRADIENT
@ PARTICLE_FIELD_ID_COUNT
@ PARTICLE_FIELD_ID_DIFFUSIVITY
@ PARTICLE_FIELD_ID_VELOCITY
PetscErrorCode BinarySearchInt64(PetscInt n, const PetscInt64 arr[], PetscInt64 key, PetscBool *found)
Performs a binary search for a key in a sorted array of PetscInt64.
#define PICURV_ALWAYS_INLINE
Forces inlining of a per-cell or per-face kernel whose size defeats the compiler's inlining heuristic...
#define RANK_NEIGHBOR_INDEX(di, dj, dk)
Index in RankNeighbors::rank of the neighbour offset (di, dj, dk), each -1, 0 or 1.
PetscBool verifyGhostUpdates
-picurv_verify_ghost_updates: test-only cross-checks of skipped or partial ghost updates,...
PetscInt64 searchLocatedCount
PetscInt64 searchLostCount
SimCtx * simCtx
Back-pointer to the master simulation context.
ParticleLocationStatus
Defines the state of a particle with respect to its location and migration status during the iterativ...
@ LOST
The search failed for a particle believed to be inside the domain.
@ EXITED
The particle crossed a domain-boundary face whose particle policy removes it.
Cmpnts max_coords
Maximum x, y, z coordinates of the bounding box.
Cmpnts diffusivitygradient
PetscInt64 searchPopulation
PetscInt currentSettlementPass
PetscInt64 searchExitedCount
Cmpnts min_coords
Minimum x, y, z coordinates of the bounding box.
PetscMPIInt destination_rank
PetscInt64 bboxGuessFallbackCount
ParticleLocationStatus location_status
PetscInt64 bboxGuessSuccessCount
PetscInt64 maxParticlePassDepth
PetscInt particlesMigratedLastStep
PetscInt particleRandomSeed
Base seed for every particle RNG stream (-particle_random_seed).
SearchMetricsState searchMetrics
PetscInt migrationPassesLastStep
Defines a 3D axis-aligned bounding box.
A 3D point or vector with PetscScalar components.
Information needed to migrate a single particle between MPI ranks.
Defines a particle's core properties for Lagrangian tracking.
The master context for the entire simulation.
User-defined context containing data specific to a single computational grid level.
Head of a generic C-style linked list.
PetscErrorCode FindOwnerOfCell(UserCtx *user, PetscInt i, PetscInt j, PetscInt k, PetscMPIInt *owner_rank)
Finds the MPI rank that owns a given global cell index.
PetscErrorCode LocateParticleOrFindMigrationTarget(UserCtx *user, const struct FacePlaneArrays *planes, Particle *particle, ParticleLocationStatus *status_out)