PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Modules | Functions
Particle-to-Grid Scattering

Functions for scattering particle data (scalar or vector) onto Eulerian grid fields by averaging contributions within each cell. More...

Collaboration diagram for Particle-to-Grid Scattering:

Modules

 Internal Scattering Helpers
 Lower-level functions used by the main scattering routines.
 

Functions

PetscErrorCode ScatterParticleFieldCellMean (UserCtx *user, ParticleFieldId particle_field_id, DM dataDM, Vec countVec, PetscBool recount, Vec meanVec)
 Cell mean of a particle field: the field summed over each cell's particles, divided by the cell's count.
 
PetscErrorCode ScatterParticleFieldToEulerField (UserCtx *user, ParticleFieldId particle_field_id, Vec eulerFieldAverageVec)
 Scatters a particle field (scalar or vector) to the corresponding Eulerian field average.
 
PetscErrorCode ScatterAllParticleFieldsToEulerFields (UserCtx *user)
 Scatters a predefined set of particle fields to their corresponding Eulerian fields.
 

Detailed Description

Functions for scattering particle data (scalar or vector) onto Eulerian grid fields by averaging contributions within each cell.

This file provides a modular set of functions to perform particle-to-grid projection, specifically calculating cell-averaged quantities from particle properties. It assumes a PETSc environment using DMDA for the grids and DMSwarm for particles.

Key Features:

Dependencies:

Function Documentation

◆ ScatterParticleFieldCellMean()

PetscErrorCode ScatterParticleFieldCellMean ( UserCtx *  user,
ParticleFieldId  particle_field_id,
DM  dataDM,
Vec  countVec,
PetscBool  recount,
Vec  meanVec 
)

Cell mean of a particle field: the field summed over each cell's particles, divided by the cell's count.

Implementation of ScatterParticleFieldCellMean().

Zeroes a ghosted accumulator, adds every local particle into its cell with AccumulateParticleField(), sums the ranks' copies into the owners (local-to-global ADD), and divides by countVec with NormalizeGridVectorByCount(); an empty cell's mean is zero. Collective.

Parameters
[in]userContext holding the swarm and the cell DM da.
[in]particle_field_idPETSC_REAL particle field to average.
[in]dataDMDMDA of the mean, with as many DOF as the field has components.
[in]countVecGlobal particles-per-cell vector on user->da; only its owned entries are read.
[in]recountPETSC_TRUE to recount user->ParticleCount (and reset user->lParticleCount) with CalculateParticleCountPerCell() before dividing; countVec is then normally user->ParticleCount.
[in,out]meanVecGlobal vector on dataDM receiving the owned means.
Returns
PetscErrorCode 0 on success.
See also
ScatterParticleFieldCellMean()

Definition at line 1725 of file interpolation.c.

1727{
1728 PetscInt data_dof = 0;
1729 Vec local_sum = NULL, sum = NULL;
1730 const ParticleFieldDescriptor *descriptor = NULL;
1731
1732 PetscFunctionBeginUser;
1734 PetscCheck(user && user->swarm && dataDM && countVec && meanVec, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1735 "Context, swarm, data DM, count and mean vectors are required.");
1736 PetscCall(ParticleFieldGetDescriptor(particle_field_id, &descriptor));
1737 PetscCall(DMDAGetInfo(dataDM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &data_dof, NULL, NULL, NULL, NULL, NULL));
1738 PetscCheck(data_dof == descriptor->components, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP,
1739 "Field '%s' has %" PetscInt_FMT " components but the data DM has DOF %" PetscInt_FMT ".",
1740 descriptor->canonical_name, descriptor->components, data_dof);
1741
1742 // Each rank's particles add into its ghosted copy; the owners sum the copies.
1743 PetscCall(DMGetLocalVector(dataDM, &local_sum));
1744 PetscCall(VecSet(local_sum, 0.0));
1745 PetscCall(AccumulateParticleField(user->swarm, particle_field_id, dataDM, local_sum));
1746 PetscCall(DMGetGlobalVector(dataDM, &sum));
1747 PetscCall(VecSet(sum, 0.0));
1748 PetscCall(DMLocalToGlobalBegin(dataDM, local_sum, ADD_VALUES, sum));
1749 PetscCall(DMLocalToGlobalEnd(dataDM, local_sum, ADD_VALUES, sum));
1750 PetscCall(DMRestoreLocalVector(dataDM, &local_sum));
1751
1752 if (recount) PetscCall(CalculateParticleCountPerCell(user));
1753 PetscCall(NormalizeGridVectorByCount(user->da, countVec, dataDM, sum, meanVec));
1754 PetscCall(DMRestoreGlobalVector(dataDM, &sum));
1756 PetscFunctionReturn(0);
1757}
PetscErrorCode CalculateParticleCountPerCell(UserCtx *user)
Counts particles in each cell of the DMDA 'da' and stores the result in user->ParticleCount.
PetscErrorCode AccumulateParticleField(DM swarm, ParticleFieldId particle_field_id, DM gridSumDM, Vec gridSumVec)
Accumulates a particle field (scalar or vector) into a target grid sum vector.
PetscErrorCode NormalizeGridVectorByCount(DM countDM, Vec countVec, DM dataDM, Vec sumVec, Vec avgVec)
Normalizes a grid vector of sums by a grid vector of counts to produce an average.
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
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:

◆ ScatterParticleFieldToEulerField()

PetscErrorCode ScatterParticleFieldToEulerField ( UserCtx *  user,
ParticleFieldId  particle_field_id,
Vec  eulerFieldAverageVec 
)

Scatters a particle field (scalar or vector) to the corresponding Eulerian field average.

This is the main user-facing function. It determines the target Eulerian DM from the particle catalog, validates the provided eulerFieldAverageVec against the target DM, and then orchestrates the scatter operation by calling ScatterParticleFieldCellMean(), recounting the particles per cell first. The final averaged result is stored IN-PLACE in eulerFieldAverageVec.

Parameters
[in]userPointer to UserCtx containing da, fda, swarm, ParticleCount.
[in]particle_field_idTyped identity of the DMSwarm field.
[in,out]eulerFieldAverageVecPre-created Vec associated with the correct target DM (implicitly da or fda). Result stored here.
Returns
PetscErrorCode 0 on success. Errors on NULL input, unrecognized field name, or incompatible target vector.

Definition at line 1761 of file interpolation.c.

1764{
1765 PetscErrorCode ierr;
1766 DM targetDM = NULL; // Will point to user->da or user->fda
1767 PetscInt expected_dof = 0; // Will be 1 or 3
1768 char msg[ERROR_MSG_BUFFER_SIZE]; // Buffer for formatted error messages
1769 const ParticleFieldDescriptor *particle_descriptor = NULL;
1770 const FieldDescriptor *eulerian_descriptor = NULL;
1771 FieldView target_view;
1772 const char *particleFieldName = NULL;
1773
1774 PetscFunctionBeginUser;
1775
1777
1778 // --- Essential Input Validation ---
1779 if (!user) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx pointer is NULL.");
1780 if (!user->swarm) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx->swarm is NULL.");
1781 if (!user->ParticleCount) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx->ParticleCount is NULL.");
1782 if (!eulerFieldAverageVec) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Output eulerFieldAverageVec is NULL.");
1783 ierr = ParticleFieldGetDescriptor(particle_field_id, &particle_descriptor); CHKERRQ(ierr);
1784 PetscCheck((particle_descriptor->capabilities & PARTICLE_FIELD_CAPABILITY_EULERIAN_SCATTER) != 0,
1785 PETSC_COMM_SELF, PETSC_ERR_SUP,
1786 "Particle field '%s' has no registered Eulerian scatter target.",
1787 particle_descriptor->canonical_name);
1788 PetscCheck(particle_descriptor->eulerian_scatter_target != FIELD_ID_INVALID,
1789 PETSC_COMM_SELF, PETSC_ERR_PLIB,
1790 "Particle field '%s' advertises scatter support without an Eulerian target.",
1791 particle_descriptor->canonical_name);
1792 particleFieldName = particle_descriptor->canonical_name;
1793 expected_dof = particle_descriptor->components;
1794 ierr = FieldGetDescriptor(particle_descriptor->eulerian_scatter_target, &eulerian_descriptor); CHKERRQ(ierr);
1795 PetscCheck(eulerian_descriptor->dof == expected_dof, PETSC_COMM_SELF, PETSC_ERR_PLIB,
1796 "Particle field '%s' has %" PetscInt_FMT " components but Eulerian target '%s' has %" PetscInt_FMT ".",
1797 particleFieldName, expected_dof, eulerian_descriptor->canonical_name, eulerian_descriptor->dof);
1798 ierr = FieldGetView(user, particle_descriptor->eulerian_scatter_target, &target_view); CHKERRQ(ierr);
1799 targetDM = target_view.dm;
1800
1801 // --- Validate the provided Target Vec's Compatibility ---
1802 DM vec_dm;
1803 PetscInt vec_dof;
1804 // Check that the provided average vector has a DM associated with it
1805 ierr = VecGetDM(eulerFieldAverageVec, &vec_dm); CHKERRQ(ierr);
1806 if (!vec_dm) {
1807 PetscSNPrintf(msg, sizeof(msg), "Provided eulerFieldAverageVec for field '%s' does not have an associated DM.", particleFieldName);
1808 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "%s", msg);
1809 }
1810 // Get the block size (DOF) of the provided vector
1811 ierr = VecGetBlockSize(eulerFieldAverageVec, &vec_dof); CHKERRQ(ierr);
1812 // Compare the vector's associated DM with the one determined by the field name
1813 if (vec_dm != targetDM) {
1814 const char *target_dm_name = "targetDM", *vec_dm_name = "vec_dm";
1815 // Get actual names if possible for a more informative error message
1816 PetscObjectGetName((PetscObject)targetDM, &target_dm_name);
1817 PetscObjectGetName((PetscObject)vec_dm, &vec_dm_name);
1818 PetscSNPrintf(msg, sizeof(msg), "Provided eulerFieldAverageVec associated with DM '%s', but field '%s' requires scatter to DM '%s'.", vec_dm_name, particleFieldName, target_dm_name);
1819 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "%s", msg);
1820 }
1821 // Compare the vector's DOF with the one expected for the field name
1822 if (vec_dof != expected_dof) {
1823 PetscSNPrintf(msg, sizeof(msg), "Field '%s' requires DOF %" PetscInt_FMT ", but provided eulerFieldAverageVec has DOF %" PetscInt_FMT ".", particleFieldName, expected_dof, vec_dof);
1824 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "%s", msg);
1825 }
1826
1827 // --- Perform Scatter using Internal Helper ---
1828 // Log intent before calling the core logic
1829 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Scattering field '%s' (DOF=%" PetscInt_FMT ").\n", particleFieldName, expected_dof);
1830 ierr = ScatterParticleFieldCellMean(user, particle_field_id, targetDM, user->ParticleCount, PETSC_TRUE,
1831 eulerFieldAverageVec); CHKERRQ(ierr);
1832
1833 LOG_ALLOW(GLOBAL, LOG_INFO, "Successfully scattered field '%s'.\n", particleFieldName);
1834
1836
1837 PetscFunctionReturn(0);
1838}
PetscErrorCode FieldGetView(UserCtx *user, FieldId field_id, FieldView *view)
Resolve the existing DM and global/local vectors for one field.
const char * canonical_name
PetscErrorCode FieldGetDescriptor(FieldId field_id, const FieldDescriptor **descriptor)
Return immutable metadata for a valid field identifier.
@ FIELD_ID_INVALID
Immutable metadata for one field identity.
Non-owning runtime objects resolved for one field and UserCtx.
PetscErrorCode ScatterParticleFieldCellMean(UserCtx *user, ParticleFieldId particle_field_id, DM dataDM, Vec countVec, PetscBool recount, Vec meanVec)
Cell mean of a particle field: the field summed over each cell's particles, divided by the cell's cou...
#define ERROR_MSG_BUFFER_SIZE
#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
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
@ PARTICLE_FIELD_CAPABILITY_EULERIAN_SCATTER
Vec ParticleCount
Definition variables.h:1276
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ScatterAllParticleFieldsToEulerFields()

PetscErrorCode ScatterAllParticleFieldsToEulerFields ( UserCtx *  user)

Scatters a predefined set of particle fields to their corresponding Eulerian fields.

This convenience function calls the unified ScatterParticleFieldToEulerField for a standard set of fields ("P", potentially others). It assumes the target Eulerian Vec objects (e.g., user->P, user->Ucat) exist in the UserCtx structure and are correctly associated with their respective DMs (user->da or user->fda). It zeros the target Vecs before scattering.

Parameters
[in,out]userPointer to the UserCtx structure containing all required DMs, Vecs (ParticleCount, target Eulerian fields like P, Ucat), and swarm.
Returns
PetscErrorCode 0 on success. Errors if prerequisites (like ParticleCount) are missing or if underlying scatter calls fail.

Definition at line 1841 of file interpolation.c.

1842{
1843 PetscErrorCode ierr;
1844 PetscFunctionBeginUser;
1846
1847 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting scattering of specified particle fields to Eulerian grids.\n");
1848
1849 // --- Pre-computation Check: Ensure Particle Counts are Ready ---
1850 if (!user->ParticleCount) {
1851 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "UserCtx->ParticleCount is NULL. Compute counts before calling ScatterAllParticleFieldsToEulerFields.");
1852 }
1853
1854 // --- Scatter Particle Field "Psi" -> Eulerian Field user->Psi (on da) ---
1855 // Check if the target Eulerian vector 'user->Psi' exists.
1856 if (user->Psi) {
1857
1858 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Scattering particle field 'Psi' to user->Psi.\n");
1859 // Zero the target vector before accumulating the new average for this step/call.
1860
1861 // Debug verification: global means are collectives, so they run only when they are logged.
1862 const PetscBool log_means = (PetscBool)((int)get_log_level() >= (int)LOG_DEBUG);
1863 PetscReal Avg_Psi = 0.0, Avg_swarm_Psi = 0.0;
1864 if (log_means) {
1865 Vec swarm_Psi;
1866 ierr = VecMean(user->Psi,&Avg_Psi); CHKERRQ(ierr);
1867 LOG_ALLOW(GLOBAL,LOG_DEBUG," Average of Scalar(Psi) before scatter: %.4f.\n",Avg_Psi);
1868 ierr = DMSwarmCreateGlobalVectorFromField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), &swarm_Psi); CHKERRQ(ierr);
1869 ierr = VecMean(swarm_Psi,&Avg_swarm_Psi); CHKERRQ(ierr);
1870 LOG_ALLOW(GLOBAL,LOG_DEBUG," Average of Particle Scalar(Psi): %.4f.\n",Avg_swarm_Psi);
1871 ierr = DMSwarmDestroyGlobalVectorFromField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), &swarm_Psi); CHKERRQ(ierr);
1872 }
1873
1874 //ierr = VecSet(user->P, 0.0); CHKERRQ(ierr);
1875 // Call the unified scatter function. It will handle DM determination and validation.
1876 // It will also error out if the *particle* field "Psi" doesn't exist in the swarm.
1877 ierr = ScatterParticleFieldToEulerField(user, PARTICLE_FIELD_ID_PSI, user->Psi); CHKERRQ(ierr);
1878 // The average leaves the empty dummy cells at zero; give them the adjacent cell's
1879 // value (no scalar flux through the boundary) so node averages near a boundary read
1880 // cell means, not a mix with zeros.
1881 ierr = UpdateDummyCells(user, FIELD_ID_PSI); CHKERRQ(ierr);
1882 ierr = UpdateCornerNodes(user, FIELD_ID_PSI); CHKERRQ(ierr);
1883 // IEM reads the cell mean through the ghosted lPsi; refresh it from the new average.
1884 ierr = UpdateLocalGhosts(user, FIELD_ID_PSI); CHKERRQ(ierr);
1885 if (log_means) {
1886 ierr = VecMean(user->Psi,&Avg_Psi); CHKERRQ(ierr);
1887 LOG_ALLOW(GLOBAL,LOG_DEBUG," Average of Scalar(Psi) after scatter: %.4f.\n",Avg_Psi);
1888 }
1889 } else {
1890 // Only log a warning if the target Eulerian field is missing in the context.
1891 LOG_ALLOW(GLOBAL, LOG_WARNING, "Skipping scatter for 'Psi': UserCtx->Psi is NULL.\n");
1892 }
1893
1894 // Additional scatterable particle fields require an explicit catalog entry
1895 // with a compatible persistent Eulerian target.
1896
1897 LOG_ALLOW(GLOBAL, LOG_INFO, "Finished scattering specified particle fields.\n");
1899 PetscFunctionReturn(0);
1900}
PetscErrorCode UpdateDummyCells(UserCtx *user, FieldId field_id)
Fills the dummy cells on the non-periodic faces of one cell-centred field.
PetscErrorCode UpdateCornerNodes(UserCtx *user, FieldId field_id)
Fills the edge and corner dummy cells of one cell-centred field.
@ FIELD_ID_PSI
PetscErrorCode ScatterParticleFieldToEulerField(UserCtx *user, ParticleFieldId particle_field_id, Vec eulerFieldAverageVec)
Scatters a particle field (scalar or vector) to the corresponding Eulerian field average.
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
const char * ParticleFieldName(ParticleFieldId field_id)
Return the canonical PETSc DMSwarm name for an ID.
@ PARTICLE_FIELD_ID_PSI
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
Here is the call graph for this function:
Here is the caller graph for this function: