PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Functions
ParticleSwarm.h File Reference

Header file for Particle Swarm management functions. More...

#include <petsc.h>
#include <petscdmswarm.h>
#include <stdbool.h>
#include <math.h>
#include "variables.h"
#include "particle_field_catalog.h"
#include "logging.h"
#include "walkingsearch.h"
#include "Metric.h"
#include "io.h"
Include dependency graph for ParticleSwarm.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

PetscErrorCode CreateParticleSwarm (UserCtx *user, PetscInt numParticles, PetscInt *particlesPerProcess)
 Creates the particle swarm, registers its fields and sizes it for this rank's share.
 
PetscErrorCode InitializeSwarm (UserCtx *user)
 Initializes the DMSwarm object within the UserCtx structure.
 
PetscErrorCode RegisterSwarmField (DM swarm, const char *fieldName, PetscInt fieldDim, PetscDataType dtype)
 Registers a swarm field without finalizing registration.
 
PetscErrorCode RegisterParticleFields (DM swarm)
 Registers necessary particle fields within the DMSwarm.
 
PetscErrorCode AssignInitialPropertiesToSwarm (UserCtx *user, PetscInt particlesPerProcess)
 Initializes all particle properties in the swarm.
 
PetscErrorCode DistributeParticles (PetscInt numParticles, PetscMPIInt rank, PetscMPIInt size, PetscInt *particlesPerProcess, PetscInt *remainder)
 Distributes particles evenly across MPI processes, handling any remainders.
 
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.
 
PetscErrorCode UpdateParticleWeights (PetscReal *d, Particle *particle)
 Updates a particle's interpolation weights based on distances to cell faces.
 
PetscErrorCode InitializeParticleSwarm (SimCtx *simCtx)
 High-level particle initialization orchestrator for a simulation run.
 
PetscErrorCode ParticleInletsCreate (SimCtx *simCtx)
 Read the inlets that inject particles from the options database.
 
PetscErrorCode ParticleInletsDestroy (SimCtx *simCtx)
 Release what ParticleInletsCreate() and InjectParticlesAtInlets() allocated.
 
PetscErrorCode InjectParticlesAtInlets (UserCtx *user)
 Add the particles that entered through each injecting inlet during this step.
 

Detailed Description

Header file for Particle Swarm management functions.

This file contains declarations of functions responsible for creating, managing, initializing, migrating, and printing particle swarms within a simulation using PETSc's DMSwarm.

Definition in file ParticleSwarm.h.

Function Documentation

◆ CreateParticleSwarm()

PetscErrorCode CreateParticleSwarm ( UserCtx *  user,
PetscInt  numParticles,
PetscInt *  particlesPerProcess 
)

Creates the particle swarm, registers its fields and sizes it for this rank's share.

Volume and Surface seeding give each rank the particles its owned cells seed (by volume, or by area on the inlet face, the stratified split of the seeding table); PointSource divides the count evenly, the first ranks taking one more. Collective.

Parameters
[in,out]userFinest-level context; receives the swarm.
[in]numParticlesTotal number of particles to create across all MPI processes.
[out]particlesPerProcessNumber of particles assigned to the local rank.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Creates the particle swarm, registers its fields and sizes it for this rank's share.

See also
CreateParticleSwarm()

Definition at line 725 of file ParticleSwarm.c.

725 {
726 PetscErrorCode ierr; // PETSc error handling variable
727 PetscMPIInt rank, size; // Variables to store MPI rank and size
728 PetscInt remainder = 0; // Remainder of particles after division
729
730 PetscFunctionBeginUser;
732 // Validate input parameters
733 if (numParticles < 0) {
734 LOG_ALLOW(GLOBAL,LOG_DEBUG, "Number of particles must not be negative. Given: %" PetscInt_FMT "\n", numParticles);
736 return PETSC_ERR_ARG_OUTOFRANGE;
737 }
738
739 // Retrieve MPI rank and size
740 rank = user->simCtx->rank;
741 size = user->simCtx->size;
742 LOG_ALLOW(GLOBAL,LOG_INFO," Domain dimensions: [%.2f,%.2f],[%.2f,%.2f],[%.2f,%.2f] \n",
743 user->Min_X,user->Max_X,user->Min_Y,user->Max_Y, user->Min_Z,user->Max_Z);
744 LOG_ALLOW_SYNC(GLOBAL,LOG_DEBUG, "[Rank %d] Local Bounding Box: [%.2f,%.2f],[%.2f,%.2f],[%.2f,%.2f] \n",
745 rank,user->bbox.min_coords.x,user->bbox.max_coords.x,
746 user->bbox.min_coords.y,user->bbox.max_coords.y,
747 user->bbox.min_coords.z,user->bbox.max_coords.z);
748 // Distribute particles among MPI processes
750 ierr = DistributeParticlesByOwnedMeasure(user, -1, numParticles, particlesPerProcess); CHKERRQ(ierr);
752 PetscCheck(user->inletFaceDefined, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE,
753 "Surface particle seeding needs an INLET face.");
754 ierr = DistributeParticlesByOwnedMeasure(user, (PetscInt)user->identifiedInletBCFace, numParticles, particlesPerProcess); CHKERRQ(ierr);
755 } else {
756 ierr = DistributeParticles(numParticles, rank, size, particlesPerProcess, &remainder); CHKERRQ(ierr);
757 }
758
759 // Initialize the DMSwarm - creates the swarm, sets the type and dimension
760 ierr = InitializeSwarm(user); CHKERRQ(ierr);
761
762 if (user->da) {
763 ierr = DMSwarmSetCellDM(user->swarm, user->da); CHKERRQ(ierr);
764 LOG_ALLOW(LOCAL,LOG_INFO,"Associated DMSwarm with Cell DM (user->da).\n");
765 } else {
766 // If user->da is essential for your simulation logic with particles, this should be a fatal error.
767 LOG_ALLOW(GLOBAL, LOG_WARNING, "user->da (Cell DM for Swarm) is NULL. Cell-based swarm operations might fail.\n");
768 // SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE, "user->da (Cell DM) is NULL but required.");
769 }
770
771 // Register particle fields (position, velocity, CellID, weight, etc.)
772 ierr = RegisterParticleFields(user->swarm); CHKERRQ(ierr);
773
774 // Set the local number of particles for this rank and spare capacity for arrivals (10% of the
775 // local count; PETSc reallocates beyond it). Every resize zeroes the whole spare region, so a
776 // buffer sized to the global count would cost each rank memory and work of order numParticles.
777 ierr = DMSwarmSetLocalSizes(user->swarm, *particlesPerProcess, *particlesPerProcess / 10); CHKERRQ(ierr);
778 LOG_ALLOW(GLOBAL,LOG_INFO, "Set local swarm size: %" PetscInt_FMT " particles.\n", *particlesPerProcess);
779
780 // Optionally, LOG_ALLOW detailed DM info in debug mode
781 if (get_log_level() >= LOG_DEBUG && is_function_allowed(__func__)) {
782 LOG_ALLOW(GLOBAL,LOG_DEBUG,"Viewing DMSwarm:\n");
783 ierr = DMView(user->swarm, PETSC_VIEWER_STDOUT_WORLD); CHKERRQ(ierr);
784 }
785
786 LOG_ALLOW(GLOBAL,LOG_INFO, "Particle swarm creation and initialization complete.\n");
787
789 PetscFunctionReturn(0);
790}
PetscErrorCode DistributeParticles(PetscInt numParticles, PetscMPIInt rank, PetscMPIInt size, PetscInt *particlesPerProcess, PetscInt *remainder)
Implementation of DistributeParticles().
static PetscErrorCode DistributeParticlesByOwnedMeasure(UserCtx *user, PetscInt face, PetscInt numParticles, PetscInt *localCount)
Number of particles this rank seeds for volumetric or surface seeding.
PetscErrorCode InitializeSwarm(UserCtx *user)
Implementation of InitializeSwarm().
PetscErrorCode RegisterParticleFields(DM swarm)
Implementation of RegisterParticleFields().
PetscBool is_function_allowed(const char *functionName)
Checks if a given function is in the allow-list.
Definition logging.c:207
#define LOG_ALLOW_SYNC(scope, level, fmt,...)
Synchronized logging macro that checks both the log level and whether the calling function is in the ...
Definition logging.h:273
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
Definition logging.h:214
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
PetscBool inletFaceDefined
Definition variables.h:1183
PetscMPIInt rank
Definition variables.h:919
BCFace identifiedInletBCFace
Definition variables.h:1184
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
@ PARTICLE_INIT_SURFACE_RANDOM
Random placement on the inlet face.
Definition variables.h:747
@ PARTICLE_INIT_VOLUME
Random volumetric distribution across the domain.
Definition variables.h:748
PetscReal Min_X
Definition variables.h:1172
Cmpnts max_coords
Maximum x, y, z coordinates of the bounding box.
Definition variables.h:214
PetscReal Max_Y
Definition variables.h:1172
Cmpnts min_coords
Minimum x, y, z coordinates of the bounding box.
Definition variables.h:213
PetscScalar x
Definition variables.h:145
ParticleInitializationType ParticleInitialization
Definition variables.h:1054
PetscScalar z
Definition variables.h:145
PetscReal Min_Z
Definition variables.h:1172
PetscReal Max_X
Definition variables.h:1172
PetscReal Min_Y
Definition variables.h:1172
PetscScalar y
Definition variables.h:145
PetscMPIInt size
Definition variables.h:920
BoundingBox bbox
Definition variables.h:1173
PetscReal Max_Z
Definition variables.h:1172
Here is the call graph for this function:
Here is the caller graph for this function:

◆ InitializeSwarm()

PetscErrorCode InitializeSwarm ( UserCtx *  user)

Initializes the DMSwarm object within the UserCtx structure.

This function creates the DMSwarm, sets its type and dimension, and configures basic swarm properties.

Parameters
[in,out]userPointer to the UserCtx structure containing simulation context.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Initializes the DMSwarm object within the UserCtx structure.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/ParticleSwarm.h.

See also
InitializeSwarm()

Definition at line 16 of file ParticleSwarm.c.

16 {
17 PetscErrorCode ierr; // Error code for PETSc functions
18
19 PetscFunctionBeginUser;
21 // Create the DMSwarm object for particle management
22 ierr = DMCreate(PETSC_COMM_WORLD, &user->swarm); CHKERRQ(ierr);
23 ierr = DMSetType(user->swarm, DMSWARM); CHKERRQ(ierr);
24 ierr = DMSetDimension(user->swarm, 3); CHKERRQ(ierr);
25 ierr = DMSwarmSetType(user->swarm, DMSWARM_BASIC); CHKERRQ(ierr);
26 LOG_ALLOW(LOCAL,LOG_INFO, "DMSwarm created and configured.\n");
27
29 PetscFunctionReturn(0);
30}
Here is the caller graph for this function:

◆ RegisterSwarmField()

PetscErrorCode RegisterSwarmField ( DM  swarm,
const char *  fieldName,
PetscInt  fieldDim,
PetscDataType  dtype 
)

Registers a swarm field without finalizing registration.

This function calls DMSwarmRegisterPetscDatatypeField for the given field, but does not finalize the registration. The finalization is deferred until all fields have been registered.

Parameters
swarm[in] The DMSwarm object.
fieldName[in] Name of the field to register.
fieldDim[in] Dimension of the field (1 for scalar, 3 for vector, etc.).
dtype[in] The datatype of the swarm field being registered.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Registers a swarm field without finalizing registration.

See also
RegisterSwarmField()

Definition at line 37 of file ParticleSwarm.c.

38{
39 PetscErrorCode ierr;
40 PetscFunctionBeginUser;
42
43 ierr = DMSwarmRegisterPetscDatatypeField(swarm, fieldName, fieldDim, dtype); CHKERRQ(ierr);
44 // PetscDataTypes is an extern char* [] defined in petscsystypes.h that gives string names for PetscDataType enums
45 LOG_ALLOW(LOCAL,LOG_DEBUG,"Registered field '%s' with dimension=%" PetscInt_FMT ", type=%s.\n",
46 fieldName, fieldDim, PetscDataTypes[dtype]);
47
49 PetscFunctionReturn(0);
50}
Here is the caller graph for this function:

◆ RegisterParticleFields()

PetscErrorCode RegisterParticleFields ( DM  swarm)

Registers necessary particle fields within the DMSwarm.

This function registers fields such as position, velocity, CellID, and weight for each particle.

Parameters
[in,out]swarmThe DMSwarm object managing the particle swarm.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Registers necessary particle fields within the DMSwarm.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/ParticleSwarm.h.

See also
RegisterParticleFields()

Definition at line 60 of file ParticleSwarm.c.

61{
62 PetscErrorCode ierr;
63 PetscFunctionBeginUser;
65
66 for (PetscInt raw_id = 0; raw_id < PARTICLE_FIELD_ID_COUNT; ++raw_id) {
67 const ParticleFieldDescriptor *descriptor = NULL;
68
69 ierr = ParticleFieldGetDescriptor((ParticleFieldId)raw_id, &descriptor); CHKERRQ(ierr);
70 if (descriptor->registration == PARTICLE_FIELD_REGISTRATION_PETSC) continue;
71
72 ierr = RegisterSwarmField(swarm, descriptor->canonical_name,
73 descriptor->components, descriptor->data_type); CHKERRQ(ierr);
74 }
75
76 // Finalize the field registration after all fields have been added
77 ierr = DMSwarmFinalizeFieldRegister(swarm); CHKERRQ(ierr);
78 LOG_ALLOW(LOCAL,LOG_INFO,"RegisterParticleFields - Finalized field registration.\n");
79
81 PetscFunctionReturn(0);
82}
PetscErrorCode RegisterSwarmField(DM swarm, const char *fieldName, PetscInt fieldDim, PetscDataType dtype)
Implementation of RegisterSwarmField().
ParticleFieldId
Compile-time identity for a persistent solver-particle field.
@ PARTICLE_FIELD_ID_COUNT
ParticleFieldRegistration registration
@ PARTICLE_FIELD_REGISTRATION_PETSC
PetscErrorCode ParticleFieldGetDescriptor(ParticleFieldId field_id, const ParticleFieldDescriptor **descriptor)
Return immutable metadata for a valid particle field ID.
Immutable metadata for one persistent particle field.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AssignInitialPropertiesToSwarm()

PetscErrorCode AssignInitialPropertiesToSwarm ( UserCtx *  user,
PetscInt  particlesPerProcess 
)

Initializes all particle properties in the swarm.

Surface seeding requires an INLET face. The basic properties (physical position, particle ID and the seeded cell) are set by InitializeParticleBasicProperties: Volume and Surface seeding stratify the particles over the cells' volume or inlet area and key every placement draw on (seed, particle ID), so the population does not depend on the rank layout. Every field the particle catalog marks for default initialization (velocity, weight, Diffusivity, DiffusivityGradient and Psi) then takes its catalog default. Collective.

Parameters
[in,out]userPointer to the UserCtx structure.
[in]particlesPerProcessNumber of particles assigned to this MPI process.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Initializes all particle properties in the swarm.

See also
AssignInitialPropertiesToSwarm()

Definition at line 620 of file ParticleSwarm.c.

622{
623 PetscErrorCode ierr;
624 PetscFunctionBeginUser;
625
627
628 // --- 0. Input Validation ---
629 if (!user) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Null user.");
630 SimCtx *simCtx = user->simCtx;
631
632 LOG_ALLOW(GLOBAL, LOG_INFO, "Initializing swarm with %" PetscInt_FMT " particles per process. Mode: %s.\n",
633 particlesPerProcess, ParticleInitializationToString(simCtx->ParticleInitialization));
634
635 // --- 1. Surface seeding needs the INLET face the boundary conditions identified ---
637 if (user->inletFaceDefined == PETSC_FALSE) {
638 LOG_ALLOW(GLOBAL, LOG_ERROR, "Particle Initialization on inlet surface selected, but no INLET face was identified from bcs.dat. Cannot proceed.\n");
639 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE, "Surface particle seeding requires an INLET face in the boundary conditions.");
640 }
641 LOG_ALLOW(GLOBAL, LOG_INFO, "Inlet face for surface seeding = %s\n", BCFaceToString((BCFace)user->identifiedInletBCFace));
642 }
643
644 // --- 2. Initialize Basic Particle Properties (Position, PID, Cell IDs placeholder) ---
645 // Placement draws are keyed on (seed, PID), so no generator state is passed in.
646 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Calling InitializeParticleBasicProperties.\n");
647 ierr = InitializeParticleBasicProperties(user, particlesPerProcess); CHKERRQ(ierr);
648 LOG_ALLOW(GLOBAL, LOG_INFO, "Successfully initialized basic particle properties.\n");
649
650 // --- 3. The catalog's default-initialized fields: velocity, weight, Diffusivity, DiffusivityGradient, Psi ---
651 {
652 PetscInt n_local = 0;
653 ierr = DMSwarmGetLocalSize(user->swarm, &n_local); CHKERRQ(ierr);
654 ierr = InitializeDefaultParticleFields(user->swarm, 0, n_local); CHKERRQ(ierr);
655 }
656 LOG_ALLOW(GLOBAL, LOG_INFO, "Successfully completed all swarm property initialization.\n");
657
658
660
661 PetscFunctionReturn(0);
662}
static PetscErrorCode InitializeParticleBasicProperties(UserCtx *user, PetscInt particlesPerProcess)
Initialize position-independent particle fields after a particle is created.
static PetscErrorCode InitializeDefaultParticleFields(DM swarm, PetscInt first, PetscInt end)
Set local particles first to end - 1 of every field the particle catalog marks PARTICLE_FIELD_CAPABIL...
const char * BCFaceToString(BCFace face)
Returns the canonical log token for a boundary-face enum value.
Definition logging.c:640
@ LOG_ERROR
Critical errors that may halt the program.
Definition logging.h:29
const char * ParticleInitializationToString(ParticleInitializationType ParticleInitialization)
Returns the canonical log token for a particle-initialization mode.
Definition logging.c:662
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
The master context for the entire simulation.
Definition variables.h:916
Here is the call graph for this function:
Here is the caller graph for this function:

◆ DistributeParticles()

PetscErrorCode DistributeParticles ( PetscInt  numParticles,
PetscMPIInt  rank,
PetscMPIInt  size,
PetscInt *  particlesPerProcess,
PetscInt *  remainder 
)

Distributes particles evenly across MPI processes, handling any remainders.

This function calculates the number of particles each MPI process should handle, distributing the remainder particles to the first few ranks if necessary.

Parameters
[in]numParticlesTotal number of particles to create across all MPI processes.
[in]rankMPI rank of the current process.
[in]sizeTotal number of MPI processes.
[out]particlesPerProcessNumber of particles assigned to the current MPI process.
[out]remainderRemainder particles when dividing numParticles by size.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Distributes particles evenly across MPI processes, handling any remainders.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/ParticleSwarm.h.

See also
DistributeParticles()

Definition at line 671 of file ParticleSwarm.c.

671 {
672
673 PetscFunctionBeginUser;
674
676 // Calculate the base number of particles per process
677 *particlesPerProcess = numParticles / size;
678 *remainder = numParticles % size;
679
680 // Distribute the remainder particles to the first 'remainder' ranks
681 if (rank < *remainder) {
682 *particlesPerProcess += 1;
683 LOG_ALLOW_SYNC(GLOBAL,LOG_INFO,"Rank %d receives an extra particle. Total: %" PetscInt_FMT "\n", rank, *particlesPerProcess);
684 } else {
685 LOG_ALLOW_SYNC(GLOBAL,LOG_INFO, "Rank %d receives %" PetscInt_FMT " particles.\n", rank, *particlesPerProcess);
686 }
687
689 PetscFunctionReturn(0);
690}
Here is the caller graph for this function:

◆ UnpackSwarmFields()

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.

This helper function populates a Particle structure using data retrieved from DMSwarm fields. PIDs, positions, cellIndices and LocStatus are required. Pass NULL for an optional field the caller does not need; it then takes a default: weights (1, 1, 1), velocity and diffusivity gradient zero, diffusivity 1, psi 0. It logs nothing: the stage that uses a particle reports its values.

Parameters
[in]iIndex of the particle in the DMSwarm.
[in]PIDsPointer to the array of particle IDs.
[in]weightsPointer to the array of particle weights.
[in]positionsPointer to the array of particle positions.
[in]cellIndicesPointer to the array of particle cell indices.
[in]velocitiesPointer to the array of particle velocities.
[in]LocStatusPointer to the array of cell location status indicators.
[in]diffusivityPointer to the array of particle diffusivities.
[in]diffusivitygradientPointer to the array of particle diffusivity gradients.
[in]psiPointer to the array of particle psi values.
[out]particlePointer to the Particle struct to initialize.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Initializes a Particle struct with data from DMSwarm fields.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/ParticleSwarm.h.

See also
UnpackSwarmFields()

Definition at line 804 of file ParticleSwarm.c.

806 {
807 PetscFunctionBeginUser;
808
810
811 // The particle's values are reported by the stage that uses them, not here: this runs
812 // several times per particle per step.
813 if (particle == NULL) {
814 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Output Particle pointer is NULL. \n");
815 }
816 if(PIDs == NULL){
817 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input PIDs pointer is NULL.\n");
818 }
819 if(positions == NULL){
820 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input positions pointer is NULL.\n");
821 }
822 if(cellIndices == NULL){
823 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input cellIndices pointer is NULL.\n");
824 }
825 if(LocStatus == NULL){
826 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input LocStatus pointer is NULL.\n");
827 }
828
829 particle->PID = PIDs[i];
830
831 // A NULL optional field is one the caller does not need; it takes the default shown.
832 if(weights == NULL){
833 particle->weights.x = 1.0;
834 particle->weights.y = 1.0;
835 particle->weights.z = 1.0;
836 }else{
837 particle->weights.x = weights[3 * i];
838 particle->weights.y = weights[3 * i + 1];
839 particle->weights.z = weights[3 * i + 2];
840 }
841
842 particle->loc.x = positions[3 * i];
843 particle->loc.y = positions[3 * i + 1];
844 particle->loc.z = positions[3 * i + 2];
845
846 if(velocities == NULL){
847 particle->vel.x = 0.0;
848 particle->vel.y = 0.0;
849 particle->vel.z = 0.0;
850 }else{
851 particle->vel.x = velocities[3 * i];
852 particle->vel.y = velocities[3 * i + 1];
853 particle->vel.z = velocities[3 * i + 2];
854 }
855
856 particle->diffusivity = (diffusivity == NULL) ? 1.0 : diffusivity[i];
857
858 if(diffusivitygradient == NULL){
859 particle->diffusivitygradient.x = 0.0;
860 particle->diffusivitygradient.y = 0.0;
861 particle->diffusivitygradient.z = 0.0;
862 }else{
863 particle->diffusivitygradient = diffusivitygradient[i];
864 }
865
866 particle->psi = (psi == NULL) ? 0.0 : psi[i];
867
868 particle->cell[0] = cellIndices[3 * i];
869 particle->cell[1] = cellIndices[3 * i + 1];
870 particle->cell[2] = cellIndices[3 * i + 2];
871
872 particle->location_status = (ParticleLocationStatus)LocStatus[i];
873
874 // The destination_rank is only set by the location search, not read from the swarm,
875 // so we initialize it to a known invalid state.
876 particle->destination_rank = MPI_PROC_NULL;
877
879
880 PetscFunctionReturn(0);
881}
#define PROFILE_HELPER_BEGIN
Marks the beginning of a profiled helper: timed only when enabled by name.
Definition logging.h:1014
#define PROFILE_HELPER_END
Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
Definition logging.h:1033
Cmpnts vel
Definition variables.h:240
PetscInt cell[3]
Definition variables.h:238
ParticleLocationStatus
Defines the state of a particle with respect to its location and migration status during the iterativ...
Definition variables.h:186
Cmpnts diffusivitygradient
Definition variables.h:245
Cmpnts loc
Definition variables.h:239
PetscMPIInt destination_rank
Definition variables.h:243
ParticleLocationStatus location_status
Definition variables.h:242
PetscReal diffusivity
Definition variables.h:244
PetscReal psi
Definition variables.h:246
Cmpnts weights
Definition variables.h:241
PetscInt64 PID
Definition variables.h:237
Here is the caller graph for this function:

◆ UpdateSwarmFields()

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.

This function writes data from the Particle struct back into the raw DMSwarm arrays. It is robust: if any array pointer is NULL, that specific field is skipped. This allows selective updating (e.g., update position but not velocity).

Parameters
[in]iIndex of the particle in the local swarm arrays.
[in]particlePointer to the Particle struct containing updated data.
[in,out]positions(Optional) Array of particle positions (size 3*n).
[in,out]velocities(Optional) Array of particle velocities (size 3*n).
[in,out]weights(Optional) Array of particle weights (size 3*n).
[in,out]cellIndices(Optional) Array of particle cell indices (size 3*n).
[in,out]status(Optional) Array of location status (size 1*n).
[in,out]diffusivity(Optional) Array of diffusivity values (size 1*n).
[in,out]diffusivitygradient(Optional) Array of diffusivity gradient values (size 3*n).
[in,out]psi(Optional) Array of scalar Psi values (size 1*n).
Returns
PetscErrorCode Returns 0 on success.

Updates DMSwarm data arrays from a Particle struct.

See also
UpdateSwarmFields()

Definition at line 887 of file ParticleSwarm.c.

896{
897 PetscFunctionBeginUser;
899
900 if (!particle) {
901 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Input Particle pointer is NULL.\n");
902 }
903
904 // --- 1. Position (x, y, z) ---
905 if (positions) {
906 positions[3 * i + 0] = particle->loc.x;
907 positions[3 * i + 1] = particle->loc.y;
908 positions[3 * i + 2] = particle->loc.z;
909 }
910
911 // --- 2. Velocity (u, v, w) ---
912 if (velocities) {
913 velocities[3 * i + 0] = particle->vel.x;
914 velocities[3 * i + 1] = particle->vel.y;
915 velocities[3 * i + 2] = particle->vel.z;
916 }
917
918 // --- 3. Weights (i, j, k) ---
919 if (weights) {
920 weights[3 * i + 0] = particle->weights.x;
921 weights[3 * i + 1] = particle->weights.y;
922 weights[3 * i + 2] = particle->weights.z;
923 }
924
925 // --- 4. Cell Indices (i, j, k) ---
926 if (cellIndices) {
927 cellIndices[3 * i + 0] = particle->cell[0];
928 cellIndices[3 * i + 1] = particle->cell[1];
929 cellIndices[3 * i + 2] = particle->cell[2];
930 }
931
932 // --- 5. Status ---
933 if (status) {
934 status[i] = (PetscInt)particle->location_status;
935 }
936
937 // --- 6. Diffusivity ---
938 if (diffusivity) {
939 diffusivity[i] = particle->diffusivity;
940 }
941
942 if(diffusivitygradient){
943 diffusivitygradient[i].x = particle->diffusivitygradient.x;
944 diffusivitygradient[i].y = particle->diffusivitygradient.y;
945 diffusivitygradient[i].z = particle->diffusivitygradient.z;
946 }
947 // --- 7. Psi ---
948 if (psi) {
949 psi[i] = particle->psi;
950 }
951
953 PetscFunctionReturn(0);
954}
Here is the caller graph for this function:

◆ UpdateParticleWeights()

PetscErrorCode UpdateParticleWeights ( PetscReal *  d,
Particle *  particle 
)

Updates a particle's interpolation weights based on distances to cell faces.

This function computes interpolation weights using distances to the six cell faces (d) and updates the weight field of the provided particle.

Parameters
[in]dPointer to an array of distances to the six cell faces.
[out]particlePointer to the Particle structure whose weights are to be updated.
Returns
PetscErrorCode Returns 0 on success, or a non-zero error code on failure.

Updates a particle's interpolation weights based on distances to cell faces.

See also
UpdateParticleWeights()

Definition at line 960 of file ParticleSwarm.c.

960 {
961
962 PetscFunctionBeginUser;
964
965 // Validate input pointers
966 if (!d || !particle) {
967 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
968 "Null pointer argument (d or particle).");
969 }
970
971
972 // Validate distances
973 for (PetscInt i = LEFT; i < NUM_FACES; i++) {
975 // A particle on a face: benign, so reported only to a VERBOSE run of this function.
977 "face distance d[%" PetscInt_FMT "] = %g <= %g; "
978 "clamping to avoid zero/negative.\n",
979 i, (double)d[i], INTERPOLATION_DISTANCE_TOLERANCE);
981 }
982 }
983
984 // Compute and update the particle's weights
985 particle->weights.x = d[LEFT] / (d[LEFT] + d[RIGHT]);
986 particle->weights.y = d[BOTTOM] / (d[BOTTOM] + d[TOP]);
987 particle->weights.z = d[BACK] / (d[FRONT] + d[BACK]);
988
989
990
992 PetscFunctionReturn(0);
993}
#define INTERPOLATION_DISTANCE_TOLERANCE
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
@ TOP
Definition variables.h:197
@ FRONT
Definition variables.h:197
@ BOTTOM
Definition variables.h:197
@ BACK
Definition variables.h:197
@ LEFT
Definition variables.h:197
@ NUM_FACES
Definition variables.h:197
@ RIGHT
Definition variables.h:197
Here is the caller graph for this function:

◆ InitializeParticleSwarm()

PetscErrorCode InitializeParticleSwarm ( SimCtx *  simCtx)

High-level particle initialization orchestrator for a simulation run.

This routine drives end-to-end swarm setup from the top-level simulation context: creation/registration of particle fields, initial placement according to configured mode, initial localization on the Eulerian grid, and startup interpolation needed before entering the main run loop.

Parameters
[in,out]simCtxMaster simulation context containing all blocks and run settings.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

High-level particle initialization orchestrator for a simulation run.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/ParticleSwarm.h.

See also
InitializeParticleSwarm()

Definition at line 1002 of file ParticleSwarm.c.

1003{
1004 PetscErrorCode ierr;
1005 PetscInt particlesPerProcess = 0;
1006 UserCtx *user = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
1007
1008 PetscFunctionBeginUser;
1010
1011 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting particle swarm setup for %" PetscInt_FMT " particles.\n", simCtx->np);
1012
1013 // --- Phase 1: Create the DMSwarm Object (Always required) ---
1014 // This creates the container and registers the fields. It does not add particles yet.
1015 ierr = CreateParticleSwarm(user, simCtx->np, &particlesPerProcess); CHKERRQ(ierr);
1016 LOG_ALLOW(GLOBAL, LOG_INFO, "DMSwarm object and fields created successfully.\n");
1017
1018
1019 // --- Phase 2: Decide whether to Initialize new particles or Load existing ones ---
1020 PetscBool should_initialize_new_particles = PETSC_FALSE;
1021 if(simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR){
1022 should_initialize_new_particles = PETSC_TRUE;
1023 }else{
1024 if (simCtx->StartStep == 0) {
1025 should_initialize_new_particles = PETSC_TRUE; // Standard fresh start
1026 } else {
1027 // It's a restart, so check the user's requested particle mode.
1028 if (strcmp(simCtx->particleRestartMode, "init") == 0) {
1029 should_initialize_new_particles = PETSC_TRUE; // User wants to re-initialize particles in a restarted flow.
1030 }
1031 }
1032 }
1033
1034 // --- Phase 3: Execute the chosen particle setup path ---
1035 if (should_initialize_new_particles) {
1036 // --- PATH A: Generate a fresh population of particles ---
1037 LOG_ALLOW(GLOBAL, LOG_INFO, "Mode: INITIALIZE. Generating new particle population.\n");
1038 ierr = AssignInitialPropertiesToSwarm(user, particlesPerProcess); CHKERRQ(ierr);
1039
1040 } else {
1041 // --- PATH B: Load particle population from restart files ---
1042 // This path is only taken if simCtx->StartStep > 0 AND simCtx->particleRestartMode == "load"
1043 LOG_ALLOW(GLOBAL, LOG_INFO, "Mode: LOAD. Loading particle population from files for step %" PetscInt_FMT ".\n", simCtx->StartStep);
1044
1045 ierr = PreCheckAndResizeSwarm(user, simCtx->StartStep, "dat"); CHKERRQ(ierr);
1046
1047 ierr = ReadAllSwarmFields(user, simCtx->StartStep); CHKERRQ(ierr);
1048 // Note: We check for file-open errors inside ReadAllSwarmFields now.
1049
1050 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle data loaded. CellID and status are preserved from file.\n");
1051 }
1052
1053 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle swarm setup complete.\n");
1054
1056 PetscFunctionReturn(0);
1057}
PetscErrorCode PreCheckAndResizeSwarm(UserCtx *user, PetscInt ti, const char *ext)
Checks particle count in the reference file and resizes the swarm if needed.
PetscErrorCode CreateParticleSwarm(UserCtx *user, PetscInt numParticles, PetscInt *particlesPerProcess)
Implementation of CreateParticleSwarm().
PetscErrorCode AssignInitialPropertiesToSwarm(UserCtx *user, PetscInt particlesPerProcess)
Implementation of AssignInitialPropertiesToSwarm().
PetscErrorCode ReadAllSwarmFields(UserCtx *user, PetscInt ti)
Reads multiple fields (positions, velocity, CellID, and weight) into a DMSwarm.
Definition io.c:1815
UserCtx * user
Definition variables.h:768
UserMG usermg
Definition variables.h:1082
PetscInt np
Definition variables.h:1049
PetscInt StartStep
Definition variables.h:926
char particleRestartMode[16]
Definition variables.h:1056
PetscInt mglevels
Definition variables.h:775
@ EXEC_MODE_POSTPROCESSOR
Definition variables.h:889
MGCtx * mgctx
Definition variables.h:778
ExecutionMode exec_mode
Definition variables.h:937
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ParticleInletsCreate()

PetscErrorCode ParticleInletsCreate ( SimCtx *  simCtx)

Read the inlets that inject particles from the options database.

Reads -particle_inlet_count, and for each inlet n, -particle_inlet_<n>_face, -particle_inlet_<n>_particles_per_cell (the mean per cell of the grid, an expression in t) and the field plan under particle_inlet_<n>_fields.

Parameters
[in,out]simCtxContext receiving the inlets; none when the count is absent or zero.
Returns
PetscErrorCode 0 on success.

Read the inlets that inject particles from the options database.

See also
ParticleInletsCreate()

Definition at line 1086 of file ParticleSwarm.c.

1087{
1088 static const char *const names[] = {"t"};
1089 PetscInt count = 0;
1090 PetscBool found = PETSC_FALSE;
1091
1092 PetscFunctionBeginUser;
1094 PetscCall(PetscOptionsGetInt(NULL, NULL, "-particle_inlet_count", &count, &found));
1095 if (!found || count == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1096 PetscCheck(count > 0 && count <= PARTICLE_INLET_FACE_COUNT, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1097 "-particle_inlet_count must be between 0 and %d (got %" PetscInt_FMT ").",
1099 PetscCheck((PetscInt64)simCtx->np < PARTICLE_INLET_PID_BASE, PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1100 "Injected particle IDs start at %" PetscInt64_FMT ", so a run with particle inlets seeds fewer "
1101 "particles than that (got %" PetscInt_FMT ").", PARTICLE_INLET_PID_BASE, simCtx->np);
1102 PetscCall(PetscCalloc1(count, &simCtx->particleInlets));
1103 simCtx->particleInletCount = count;
1104 for (PetscInt n = 0; n < count; ++n) {
1105 struct ParticleInlet *inlet = &simCtx->particleInlets[n];
1106 char option[256], text[4096];
1107 PetscInt face = -1;
1108
1109 PetscCall(PetscSNPrintf(option, sizeof(option), "-particle_inlet_%" PetscInt_FMT "_face", n));
1110 PetscCall(PetscOptionsGetInt(NULL, NULL, option, &face, &found));
1111 PetscCheck(found && face >= 0 && face < PARTICLE_INLET_FACE_COUNT, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
1112 "%s must name a face from 0 to %d.", option, PARTICLE_INLET_FACE_COUNT - 1);
1113 inlet->face = (BCFace)face;
1114 PetscCall(PetscSNPrintf(option, sizeof(option), "-particle_inlet_%" PetscInt_FMT "_particles_per_cell", n));
1115 PetscCall(PetscOptionsGetString(NULL, NULL, option, text, sizeof(text), &found));
1116 PetscCheck(found, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "%s is missing.", option);
1117 PetscCall(PicurvExpressionCompile(text, names, 1, PETSC_FALSE, &inlet->particles_per_cell));
1118 PetscCall(PetscSNPrintf(option, sizeof(option), "particle_inlet_%" PetscInt_FMT "_fields", n));
1119 PetscCall(ParticleFieldPlanCreate(option, &inlet->plan));
1120 PetscCheck(!inlet->plan || !VerificationScalarOverrideActive(simCtx), PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
1121 "An inlet's particle field values cannot be combined with the verification scalar source, "
1122 "which prescribes Psi at every step.");
1123 }
1125 PetscFunctionReturn(0);
1126}
PetscErrorCode ParticleFieldPlanCreate(const char *prefix, ParticleFieldPlan **plan)
Read a plan from the options database.
#define PARTICLE_INLET_PID_BASE
ParticleFieldPlan * plan
This inlet's field values; NULL uses the case's.
PicurvExpression * particles_per_cell
Mean particles per cell the entering fluid carries, in t.
#define PARTICLE_INLET_FACE_COUNT
One inlet face that injects particles.
PetscErrorCode PicurvExpressionCompile(const char *text, const char *const *names, PetscInt name_count, PetscBool allow_random, PicurvExpression **expression)
Compile one expression against a list of variable names.
Definition expression.c:551
PetscInt particleInletCount
Entries of particleInlets.
Definition variables.h:1065
struct ParticleInlet * particleInlets
Inlet faces that inject particles, or NULL.
Definition variables.h:1064
PetscBool VerificationScalarOverrideActive(const SimCtx *simCtx)
Reports whether a verification-only scalar override is active.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ParticleInletsDestroy()

PetscErrorCode ParticleInletsDestroy ( SimCtx *  simCtx)

Release what ParticleInletsCreate() and InjectParticlesAtInlets() allocated.

Parameters
[in,out]simCtxContext holding the inlets.
Returns
PetscErrorCode 0 on success.

Release what ParticleInletsCreate() and InjectParticlesAtInlets() allocated.

See also
ParticleInletsDestroy()

Definition at line 1132 of file ParticleSwarm.c.

1133{
1134 PetscFunctionBeginUser;
1136 for (PetscInt n = 0; n < simCtx->particleInletCount; ++n) {
1137 struct ParticleInlet *inlet = &simCtx->particleInlets[n];
1138 PetscCall(PicurvExpressionDestroy(&inlet->particles_per_cell));
1139 PetscCall(ParticleFieldPlanDestroy(&inlet->plan));
1140 if (inlet->table_built) PetscCall(FreeSeedingCellTable(&inlet->table));
1141 }
1142 PetscCall(PetscFree(simCtx->particleInlets));
1143 simCtx->particleInletCount = 0;
1145 PetscFunctionReturn(0);
1146}
PetscErrorCode ParticleFieldPlanDestroy(ParticleFieldPlan **plan)
Free a plan and its compiled expressions.
SeedingCellTable table
The owned cells on the face; built at the first injection.
static PetscErrorCode FreeSeedingCellTable(SeedingCellTable *table)
Free the arrays of a SeedingCellTable.
PetscBool table_built
PetscErrorCode PicurvExpressionDestroy(PicurvExpression **expression)
Free a compiled expression.
Definition expression.c:818
Here is the call graph for this function:
Here is the caller graph for this function:

◆ InjectParticlesAtInlets()

PetscErrorCode InjectParticlesAtInlets ( UserCtx *  user)

Add the particles that entered through each injecting inlet during this step.

Collective. A face cell receives on average n (u.A) dt particles, none where the flow leaves, so the entering fluid has number density n whatever its velocity profile. Counts, positions and identities come from keyed draws on the grid position, the step and the particle, so they carry no state and do not depend on the rank layout. A particle is placed just inside the face, by area and inward velocity, and its field values are set there, where it crossed. It then moves in by a uniform share of dt times the velocity the configured interpolation method gives at that point (the face cell's mean inward velocity where the cell has none) plus this step's Brownian kick from the face cell's diffusivity. The new particles are left NEEDS_LOCATION for the settlement that follows. Writes particle_injection.csv.

Parameters
[in,out]userFinest-level context of the block holding the swarm; reads lUcont, lCoor, the face-normal metric, lDiffusivity, and the interpolated velocity's sources (lUcat, or lUcont and the metrics for FaceFlux).
Returns
PetscErrorCode 0 on success; an error on a face that is not an INLET, an invalid number density, or a particle-ID or particle-count limit being reached.

Add the particles that entered through each injecting inlet during this step.

See also
InjectParticlesAtInlets()

Definition at line 1327 of file ParticleSwarm.c.

1328{
1329 SimCtx *simCtx = user->simCtx;
1330 PetscReal local[PARTICLE_INLET_FACE_COUNT][PARTICLE_INLET_SUMS] = {{0.0}};
1332 ParticleFieldEvent event = {0.0, 0};
1333 PetscInt64 faces = 0, first_id;
1334 VelocityPointInterpolator *velocity = NULL;
1335
1336 PetscFunctionBeginUser;
1338 if (simCtx->particleInletCount == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1339 {
1340 const PetscInt64 cells[3] = {user->info.mx - 2, user->info.my - 2, user->info.mz - 2};
1341 faces = 2 * (cells[0] * cells[1] + cells[1] * cells[2] + cells[2] * cells[0]);
1342 }
1343 first_id = (PetscInt64)simCtx->step * faces;
1344 PetscCheck((__int128)(simCtx->step + 1) * faces * PARTICLE_INLET_PIDS_PER_CELL + PARTICLE_INLET_PID_BASE < (__int128)PARTICLE_PID_LIMIT,
1345 PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
1346 "Step %" PetscInt_FMT " on a grid with %" PetscInt64_FMT " boundary face cells passes the last particle ID a "
1347 "checkpoint can store (2^53).", simCtx->step, faces);
1348 PetscCall(PicurvPhysicalTime(simCtx, simCtx->ti, &event.physical_time));
1349 PetscCall(InterpolateVelocityAtPointBegin(user, &velocity));
1350
1351 PetscReal cells_per_volume = 0.0;
1352 PetscBool have_cells_per_volume = PETSC_FALSE; /* computed when an inlet first needs it */
1353 for (PetscInt n = 0; n < simCtx->particleInletCount; ++n) {
1354 struct ParticleInlet *inlet = &simCtx->particleInlets[n];
1355
1356 if (!inlet->table_built) {
1357 const Cmpnts ***coor = NULL;
1358 PetscCheck(user->boundary_faces[inlet->face].mathematical_type == INLET, PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
1359 "Face %s injects particles but is not an INLET.", BCFaceToString(inlet->face));
1360 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCoor, (void *)&coor));
1361 PetscCall(BuildSeedingCellTable(user, coor, (PetscInt)inlet->face, 0, PETSC_TRUE, &inlet->table));
1362 if (!have_cells_per_volume) {
1363 /* particles_per_cell is a mean over the grid: cells over volume makes it a density,
1364 with the volume Volume seeding measures. table_built is the same on every rank,
1365 so all reduce. */
1366 SeedingCellTable volume;
1367
1368 PetscCall(BuildSeedingCellTable(user, coor, -1, 0, PETSC_FALSE, &volume));
1369 cells_per_volume = (PetscReal)(user->info.mx - 2) * (user->info.my - 2) * (user->info.mz - 2) / volume.total;
1370 PetscCall(FreeSeedingCellTable(&volume));
1371 have_cells_per_volume = PETSC_TRUE;
1372 }
1373 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCoor, (void *)&coor));
1375 inlet->table_built = PETSC_TRUE;
1376 }
1377 PetscCall(InjectAtInlet(user, inlet, &event, first_id, velocity, local[n]));
1378 }
1379 PetscCall(InterpolateVelocityAtPointEnd(&velocity));
1380
1381 PetscCallMPI(MPI_Allreduce(local, global, PARTICLE_INLET_FACE_COUNT * PARTICLE_INLET_SUMS, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1382 if (simCtx->rank == 0) {
1383 FILE *file = NULL;
1384
1385 PetscCall(PicurvOpenDiagnosticsCsv(simCtx, simCtx->analysis_dir, "particle_injection.csv",
1386 "step,physical_time,face,flow_rate,expected,injected,psi", &file));
1387 for (PetscInt n = 0; n < simCtx->particleInletCount; ++n) {
1388 fprintf(file, "%d,%.10e,%s,%.10e,%.10e,%.0f,%.10e\n", (int)simCtx->step, (double)event.physical_time,
1389 BCFaceToString(simCtx->particleInlets[n].face), (double)global[n][0], (double)global[n][1],
1390 (double)global[n][2], (double)global[n][3]);
1391 }
1392 PetscCheck(fclose(file) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE, "Unable to close the particle-injection diagnostics file.");
1393 }
1394 {
1395 PetscInt n_local = 0;
1396 PetscInt64 local_total, total = 0;
1397 char object[128];
1398
1399 PetscCall(DMSwarmGetLocalSize(user->swarm, &n_local));
1400 local_total = n_local;
1401 PetscCallMPI(MPI_Allreduce(&local_total, &total, 1, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD));
1402 PetscCall(PetscSNPrintf(object, sizeof(object), "the %" PetscInt64_FMT " particles after injection (three components each)", total));
1403 PetscCall(PicurvCheckPetscIntRange(PETSC_COMM_WORLD, 3 * total, object));
1404 }
1406 PetscFunctionReturn(0);
1407}
When and why a plan is applied.
#define PARTICLE_INLET_SUMS
PetscReal cells_per_volume
The grid's cells over its volume, set with the table.
static PetscErrorCode BuildSeedingCellTable(UserCtx *user, const Cmpnts ***coor, PetscInt face, PetscInt numParticles, PetscBool build_bound, SeedingCellTable *table)
Decide which particles each owned cell seeds, the same way at every rank layout.
#define PARTICLE_INLET_PIDS_PER_CELL
PetscReal total
Measure of every cell on every rank: the domain's volume or the face's area.
#define PARTICLE_PID_LIMIT
static PetscErrorCode InjectAtInlet(UserCtx *user, struct ParticleInlet *inlet, const ParticleFieldEvent *event, PetscInt64 first_id, const VelocityPointInterpolator *velocity, PetscReal sums[4])
Add one inlet's particles for this step.
The owned cells a seeding mode places particles in, and which particles each gets.
The arrays one method's point evaluation reads.
PetscErrorCode InterpolateVelocityAtPointEnd(VelocityPointInterpolator **interp)
Closes the arrays InterpolateVelocityAtPointBegin() opened.
PetscErrorCode InterpolateVelocityAtPointBegin(UserCtx *user, VelocityPointInterpolator **interp)
Opens the arrays for evaluating the particle velocity at points, with the configured interpolation me...
PetscErrorCode PicurvPhysicalTime(const SimCtx *simCtx, PetscReal solver_time, PetscReal *physical)
Convert a solver time to physical seconds, t * L_ref / U_ref.
Definition io.c:2986
static PetscErrorCode PicurvOpenDiagnosticsCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header, FILE **file)
Opens a per-step diagnostics CSV: PicurvOpenRunCsv() with the common settings.
Definition logging.h:1197
PetscErrorCode PicurvCheckPetscIntRange(MPI_Comm comm, PetscInt64 entries, const char *object)
Refuse a PETSc object whose global size this build's PetscInt cannot index.
Definition setup.c:102
@ INLET
Definition variables.h:323
BoundaryFaceConfig boundary_faces[6]
Definition variables.h:1182
char analysis_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:942
Vec lCoor
Definition variables.h:1243
PetscInt step
Definition variables.h:924
DMDALocalInfo info
Definition variables.h:1169
BCType mathematical_type
Definition variables.h:426
PetscReal ti
Definition variables.h:925
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Here is the call graph for this function:
Here is the caller graph for this function: