xref: /petsc/src/ts/tutorials/hamiltonian/ex2.c (revision 6a210b70a61472cf8733db59e8a3fa68f6578c01)
18214e71cSJoe static char help[] = "Landau Damping/Two Stream instability test using Vlasov-Poisson equations\n";
2b80bf5b1SJoe Pusztay 
38214e71cSJoe /*
48214e71cSJoe   To run the code with particles sinusoidally perturbed in x space use the test "pp_poisson_bsi_1d_4" or "pp_poisson_bsi_2d_4"
58214e71cSJoe   According to Lukas, good damping results come at ~16k particles per cell
68214e71cSJoe 
78214e71cSJoe   To visualize the efield use
88214e71cSJoe 
98214e71cSJoe     -monitor_efield
108214e71cSJoe 
118214e71cSJoe   To visualize the swarm distribution use
128214e71cSJoe 
138214e71cSJoe     -ts_monitor_hg_swarm
148214e71cSJoe 
158214e71cSJoe   To visualize the particles, we can use
168214e71cSJoe 
178214e71cSJoe     -ts_monitor_sp_swarm -ts_monitor_sp_swarm_retain 0 -ts_monitor_sp_swarm_phase 1 -draw_size 500,500
188214e71cSJoe 
198214e71cSJoe */
20b80bf5b1SJoe Pusztay #include <petscts.h>
218214e71cSJoe #include <petscdmplex.h>
228214e71cSJoe #include <petscdmswarm.h>
238214e71cSJoe #include <petscfe.h>
248214e71cSJoe #include <petscds.h>
258214e71cSJoe #include <petscbag.h>
268214e71cSJoe #include <petscdraw.h>
278214e71cSJoe #include <petsc/private/dmpleximpl.h>  /* For norm and dot */
288214e71cSJoe #include <petsc/private/petscfeimpl.h> /* For interpolation */
298214e71cSJoe #include "petscdm.h"
308214e71cSJoe #include "petscdmlabel.h"
318214e71cSJoe 
328214e71cSJoe PETSC_EXTERN PetscErrorCode stream(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
338214e71cSJoe PETSC_EXTERN PetscErrorCode line(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
348214e71cSJoe 
358214e71cSJoe const char *EMTypes[] = {"primal", "mixed", "coulomb", "none", "EMType", "EM_", NULL};
368214e71cSJoe typedef enum {
378214e71cSJoe   EM_PRIMAL,
388214e71cSJoe   EM_MIXED,
398214e71cSJoe   EM_COULOMB,
408214e71cSJoe   EM_NONE
418214e71cSJoe } EMType;
428214e71cSJoe 
438214e71cSJoe typedef enum {
448214e71cSJoe   V0,
458214e71cSJoe   X0,
468214e71cSJoe   T0,
478214e71cSJoe   M0,
488214e71cSJoe   Q0,
498214e71cSJoe   PHI0,
508214e71cSJoe   POISSON,
518214e71cSJoe   VLASOV,
528214e71cSJoe   SIGMA,
538214e71cSJoe   NUM_CONSTANTS
548214e71cSJoe } ConstantType;
558214e71cSJoe typedef struct {
568214e71cSJoe   PetscScalar v0; /* Velocity scale, often the thermal velocity */
578214e71cSJoe   PetscScalar t0; /* Time scale */
588214e71cSJoe   PetscScalar x0; /* Space scale */
598214e71cSJoe   PetscScalar m0; /* Mass scale */
608214e71cSJoe   PetscScalar q0; /* Charge scale */
618214e71cSJoe   PetscScalar kb;
628214e71cSJoe   PetscScalar epsi0;
638214e71cSJoe   PetscScalar phi0;          /* Potential scale */
648214e71cSJoe   PetscScalar poissonNumber; /* Non-Dimensional Poisson Number */
658214e71cSJoe   PetscScalar vlasovNumber;  /* Non-Dimensional Vlasov Number */
668214e71cSJoe   PetscReal   sigma;         /* Nondimensional charge per length in x */
678214e71cSJoe } Parameter;
68b80bf5b1SJoe Pusztay 
69b80bf5b1SJoe Pusztay typedef struct {
708214e71cSJoe   PetscBag    bag;            /* Problem parameters */
718214e71cSJoe   PetscBool   error;          /* Flag for printing the error */
728214e71cSJoe   PetscBool   efield_monitor; /* Flag to show electric field monitor */
738214e71cSJoe   PetscBool   initial_monitor;
748214e71cSJoe   PetscBool   fake_1D;           /* Run simulation in 2D but zeroing second dimension */
758214e71cSJoe   PetscBool   perturbed_weights; /* Uniformly sample x,v space with gaussian weights */
768214e71cSJoe   PetscBool   poisson_monitor;
778214e71cSJoe   PetscInt    ostep; /* print the energy at each ostep time steps */
788214e71cSJoe   PetscInt    numParticles;
798214e71cSJoe   PetscReal   timeScale;              /* Nondimensionalizing time scale */
808214e71cSJoe   PetscReal   charges[2];             /* The charges of each species */
818214e71cSJoe   PetscReal   masses[2];              /* The masses of each species */
828214e71cSJoe   PetscReal   thermal_energy[2];      /* Thermal Energy (used to get other constants)*/
838214e71cSJoe   PetscReal   cosine_coefficients[2]; /*(alpha, k)*/
848214e71cSJoe   PetscReal   totalWeight;
858214e71cSJoe   PetscReal   stepSize;
868214e71cSJoe   PetscInt    steps;
878214e71cSJoe   PetscReal   initVel;
888214e71cSJoe   EMType      em; /* Type of electrostatic model */
898214e71cSJoe   SNES        snes;
908214e71cSJoe   PetscDraw   drawef;
918214e71cSJoe   PetscDrawLG drawlg_ef;
928214e71cSJoe   PetscDraw   drawic_x;
938214e71cSJoe   PetscDraw   drawic_v;
948214e71cSJoe   PetscDraw   drawic_w;
958214e71cSJoe   PetscDrawHG drawhgic_x;
968214e71cSJoe   PetscDrawHG drawhgic_v;
978214e71cSJoe   PetscDrawHG drawhgic_w;
988214e71cSJoe   PetscDraw   EDraw;
998214e71cSJoe   PetscDraw   RhoDraw;
1008214e71cSJoe   PetscDraw   PotDraw;
1018214e71cSJoe   PetscDrawSP EDrawSP;
1028214e71cSJoe   PetscDrawSP RhoDrawSP;
1038214e71cSJoe   PetscDrawSP PotDrawSP;
1048214e71cSJoe   PetscBool   monitor_positions; /* Flag to show particle positins at each time step */
1058214e71cSJoe   PetscDraw   positionDraw;
1068214e71cSJoe   PetscDrawSP positionDrawSP;
1078214e71cSJoe   DM          swarm;
1088214e71cSJoe   PetscRandom random;
1098214e71cSJoe   PetscBool   twostream;
1108214e71cSJoe   PetscBool   checkweights;
1118214e71cSJoe   PetscInt    checkVRes; /* Flag to check/output velocity residuals for nightly tests */
112b80bf5b1SJoe Pusztay } AppCtx;
113b80bf5b1SJoe Pusztay 
114d71ae5a4SJacob Faibussowitsch static PetscErrorCode ProcessOptions(MPI_Comm comm, AppCtx *options)
115d71ae5a4SJacob Faibussowitsch {
116b80bf5b1SJoe Pusztay   PetscFunctionBeginUser;
1178214e71cSJoe   PetscInt d                      = 2;
1188214e71cSJoe   PetscInt maxSpecies             = 2;
1198214e71cSJoe   options->error                  = PETSC_FALSE;
1208214e71cSJoe   options->efield_monitor         = PETSC_FALSE;
1218214e71cSJoe   options->initial_monitor        = PETSC_FALSE;
1228214e71cSJoe   options->fake_1D                = PETSC_FALSE;
1238214e71cSJoe   options->perturbed_weights      = PETSC_FALSE;
1248214e71cSJoe   options->poisson_monitor        = PETSC_FALSE;
1258214e71cSJoe   options->ostep                  = 100;
1268214e71cSJoe   options->timeScale              = 2.0e-14;
1278214e71cSJoe   options->charges[0]             = -1.0;
1288214e71cSJoe   options->charges[1]             = 1.0;
1298214e71cSJoe   options->masses[0]              = 1.0;
1308214e71cSJoe   options->masses[1]              = 1000.0;
1318214e71cSJoe   options->thermal_energy[0]      = 1.0;
1328214e71cSJoe   options->thermal_energy[1]      = 1.0;
1338214e71cSJoe   options->cosine_coefficients[0] = 0.01;
1348214e71cSJoe   options->cosine_coefficients[1] = 0.5;
1358214e71cSJoe   options->initVel                = 1;
1368214e71cSJoe   options->totalWeight            = 1.0;
1378214e71cSJoe   options->drawef                 = NULL;
1388214e71cSJoe   options->drawlg_ef              = NULL;
1398214e71cSJoe   options->drawic_x               = NULL;
1408214e71cSJoe   options->drawic_v               = NULL;
1418214e71cSJoe   options->drawic_w               = NULL;
1428214e71cSJoe   options->drawhgic_x             = NULL;
1438214e71cSJoe   options->drawhgic_v             = NULL;
1448214e71cSJoe   options->drawhgic_w             = NULL;
1458214e71cSJoe   options->EDraw                  = NULL;
1468214e71cSJoe   options->RhoDraw                = NULL;
1478214e71cSJoe   options->PotDraw                = NULL;
1488214e71cSJoe   options->EDrawSP                = NULL;
1498214e71cSJoe   options->RhoDrawSP              = NULL;
1508214e71cSJoe   options->PotDrawSP              = NULL;
1518214e71cSJoe   options->em                     = EM_COULOMB;
1528214e71cSJoe   options->numParticles           = 32768;
1538214e71cSJoe   options->monitor_positions      = PETSC_FALSE;
1548214e71cSJoe   options->positionDraw           = NULL;
1558214e71cSJoe   options->positionDrawSP         = NULL;
1568214e71cSJoe   options->twostream              = PETSC_FALSE;
1578214e71cSJoe   options->checkweights           = PETSC_FALSE;
1588214e71cSJoe   options->checkVRes              = 0;
159b80bf5b1SJoe Pusztay 
1608214e71cSJoe   PetscOptionsBegin(comm, "", "Landau Damping and Two Stream options", "DMSWARM");
1618214e71cSJoe   PetscCall(PetscOptionsBool("-error", "Flag to print the error", "ex2.c", options->error, &options->error, NULL));
1628214e71cSJoe   PetscCall(PetscOptionsBool("-monitor_efield", "Flag to show efield plot", "ex2.c", options->efield_monitor, &options->efield_monitor, NULL));
1638214e71cSJoe   PetscCall(PetscOptionsBool("-monitor_ics", "Flag to show initial condition histograms", "ex2.c", options->initial_monitor, &options->initial_monitor, NULL));
1648214e71cSJoe   PetscCall(PetscOptionsBool("-monitor_positions", "The flag to show particle positions", "ex2.c", options->monitor_positions, &options->monitor_positions, NULL));
1658214e71cSJoe   PetscCall(PetscOptionsBool("-monitor_poisson", "The flag to show charges, Efield and potential solve", "ex2.c", options->poisson_monitor, &options->poisson_monitor, NULL));
1668214e71cSJoe   PetscCall(PetscOptionsBool("-fake_1D", "Flag to run a 1D simulation (but really in 2D)", "ex2.c", options->fake_1D, &options->fake_1D, NULL));
1678214e71cSJoe   PetscCall(PetscOptionsBool("-twostream", "Run two stream instability", "ex2.c", options->twostream, &options->twostream, NULL));
1688214e71cSJoe   PetscCall(PetscOptionsBool("-perturbed_weights", "Flag to run uniform sampling with perturbed weights", "ex2.c", options->perturbed_weights, &options->perturbed_weights, NULL));
1698214e71cSJoe   PetscCall(PetscOptionsBool("-check_weights", "Ensure all particle weights are positive", "ex2.c", options->checkweights, &options->checkweights, NULL));
1708214e71cSJoe   PetscCall(PetscOptionsInt("-check_vel_res", "Check particle velocity residuals for nightly tests", "ex2.c", options->checkVRes, &options->checkVRes, NULL));
1718214e71cSJoe   PetscCall(PetscOptionsInt("-output_step", "Number of time steps between output", "ex2.c", options->ostep, &options->ostep, NULL));
1728214e71cSJoe   PetscCall(PetscOptionsReal("-timeScale", "Nondimensionalizing time scale", "ex2.c", options->timeScale, &options->timeScale, NULL));
1738214e71cSJoe   PetscCall(PetscOptionsReal("-initial_velocity", "Initial velocity of perturbed particle", "ex2.c", options->initVel, &options->initVel, NULL));
1748214e71cSJoe   PetscCall(PetscOptionsReal("-total_weight", "Total weight of all particles", "ex2.c", options->totalWeight, &options->totalWeight, NULL));
1758214e71cSJoe   PetscCall(PetscOptionsRealArray("-cosine_coefficients", "Amplitude and frequency of cosine equation used in initialization", "ex2.c", options->cosine_coefficients, &d, NULL));
1768214e71cSJoe   PetscCall(PetscOptionsRealArray("-charges", "Species charges", "ex2.c", options->charges, &maxSpecies, NULL));
1778214e71cSJoe   PetscCall(PetscOptionsEnum("-em_type", "Type of electrostatic solver", "ex2.c", EMTypes, (PetscEnum)options->em, (PetscEnum *)&options->em, NULL));
178d0609cedSBarry Smith   PetscOptionsEnd();
1793ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
180b80bf5b1SJoe Pusztay }
181b80bf5b1SJoe Pusztay 
1828214e71cSJoe static PetscErrorCode SetupContext(DM dm, DM sw, AppCtx *user)
1838214e71cSJoe {
1848214e71cSJoe   PetscFunctionBeginUser;
1858214e71cSJoe   if (user->efield_monitor) {
1868214e71cSJoe     PetscDrawAxis axis_ef;
1878214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "monitor_efield", 0, 300, 400, 300, &user->drawef));
1888214e71cSJoe     PetscCall(PetscDrawSetSave(user->drawef, "ex9_Efield.png"));
1898214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->drawef));
1908214e71cSJoe     PetscCall(PetscDrawLGCreate(user->drawef, 1, &user->drawlg_ef));
1918214e71cSJoe     PetscCall(PetscDrawLGGetAxis(user->drawlg_ef, &axis_ef));
1928214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis_ef, "Electron Electric Field", "time", "E_max"));
1938214e71cSJoe     PetscCall(PetscDrawLGSetLimits(user->drawlg_ef, 0., user->steps * user->stepSize, -10., 0.));
1948214e71cSJoe     PetscCall(PetscDrawAxisSetLimits(axis_ef, 0., user->steps * user->stepSize, -10., 0.));
1958214e71cSJoe   }
1968214e71cSJoe   if (user->initial_monitor) {
1978214e71cSJoe     PetscDrawAxis axis1, axis2, axis3;
1988214e71cSJoe     PetscReal     dmboxlower[2], dmboxupper[2];
1998214e71cSJoe     PetscInt      dim, cStart, cEnd;
2008214e71cSJoe     PetscCall(DMGetDimension(sw, &dim));
2018214e71cSJoe     PetscCall(DMGetBoundingBox(dm, dmboxlower, dmboxupper));
2028214e71cSJoe     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
2038214e71cSJoe 
2048214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "monitor_initial_conditions_x", 0, 300, 400, 300, &user->drawic_x));
2058214e71cSJoe     PetscCall(PetscDrawSetSave(user->drawic_x, "ex9_ic_x.png"));
2068214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->drawic_x));
2076497c311SBarry Smith     PetscCall(PetscDrawHGCreate(user->drawic_x, (int)dim, &user->drawhgic_x));
2088214e71cSJoe     PetscCall(PetscDrawHGGetAxis(user->drawhgic_x, &axis1));
2096497c311SBarry Smith     PetscCall(PetscDrawHGSetNumberBins(user->drawhgic_x, (int)(cEnd - cStart)));
2108214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis1, "Initial X Distribution", "X", "counts"));
2118214e71cSJoe     PetscCall(PetscDrawAxisSetLimits(axis1, dmboxlower[0], dmboxupper[0], 0, 1500));
2128214e71cSJoe 
2138214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "monitor_initial_conditions_v", 400, 300, 400, 300, &user->drawic_v));
2148214e71cSJoe     PetscCall(PetscDrawSetSave(user->drawic_v, "ex9_ic_v.png"));
2158214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->drawic_v));
2166497c311SBarry Smith     PetscCall(PetscDrawHGCreate(user->drawic_v, (int)dim, &user->drawhgic_v));
2178214e71cSJoe     PetscCall(PetscDrawHGGetAxis(user->drawhgic_v, &axis2));
2188214e71cSJoe     PetscCall(PetscDrawHGSetNumberBins(user->drawhgic_v, 1000));
2198214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis2, "Initial V_x Distribution", "V", "counts"));
2208214e71cSJoe     PetscCall(PetscDrawAxisSetLimits(axis2, -1, 1, 0, 1500));
2218214e71cSJoe 
2228214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "monitor_initial_conditions_w", 800, 300, 400, 300, &user->drawic_w));
2238214e71cSJoe     PetscCall(PetscDrawSetSave(user->drawic_w, "ex9_ic_w.png"));
2248214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->drawic_w));
2256497c311SBarry Smith     PetscCall(PetscDrawHGCreate(user->drawic_w, (int)dim, &user->drawhgic_w));
2268214e71cSJoe     PetscCall(PetscDrawHGGetAxis(user->drawhgic_w, &axis3));
2278214e71cSJoe     PetscCall(PetscDrawHGSetNumberBins(user->drawhgic_w, 10));
2288214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis3, "Initial W Distribution", "weight", "counts"));
2298214e71cSJoe     PetscCall(PetscDrawAxisSetLimits(axis3, 0, 0.01, 0, 5000));
2308214e71cSJoe   }
2318214e71cSJoe   if (user->monitor_positions) {
2328214e71cSJoe     PetscDrawAxis axis;
2338214e71cSJoe 
2348214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "position_monitor_species1", 0, 0, 400, 300, &user->positionDraw));
2358214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->positionDraw));
2368214e71cSJoe     PetscCall(PetscDrawSPCreate(user->positionDraw, 10, &user->positionDrawSP));
2378214e71cSJoe     PetscCall(PetscDrawSPSetDimension(user->positionDrawSP, 1));
2388214e71cSJoe     PetscCall(PetscDrawSPGetAxis(user->positionDrawSP, &axis));
2398214e71cSJoe     PetscCall(PetscDrawSPReset(user->positionDrawSP));
2408214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis, "Particles", "x", "v"));
2418214e71cSJoe     PetscCall(PetscDrawSetSave(user->positionDraw, "ex9_pos.png"));
2428214e71cSJoe   }
2438214e71cSJoe   if (user->poisson_monitor) {
2448214e71cSJoe     PetscDrawAxis axis_E, axis_Rho, axis_Pot;
2458214e71cSJoe 
2468214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "Efield_monitor", 0, 0, 400, 300, &user->EDraw));
2478214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->EDraw));
2488214e71cSJoe     PetscCall(PetscDrawSPCreate(user->EDraw, 10, &user->EDrawSP));
2498214e71cSJoe     PetscCall(PetscDrawSPSetDimension(user->EDrawSP, 1));
2508214e71cSJoe     PetscCall(PetscDrawSPGetAxis(user->EDrawSP, &axis_E));
2518214e71cSJoe     PetscCall(PetscDrawSPReset(user->EDrawSP));
2528214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis_E, "Particles", "x", "E"));
2538214e71cSJoe     PetscCall(PetscDrawSetSave(user->EDraw, "ex9_E_spatial.png"));
2548214e71cSJoe 
2558214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "rho_monitor", 0, 0, 400, 300, &user->RhoDraw));
2568214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->RhoDraw));
2578214e71cSJoe     PetscCall(PetscDrawSPCreate(user->RhoDraw, 10, &user->RhoDrawSP));
2588214e71cSJoe     PetscCall(PetscDrawSPSetDimension(user->RhoDrawSP, 1));
2598214e71cSJoe     PetscCall(PetscDrawSPGetAxis(user->RhoDrawSP, &axis_Rho));
2608214e71cSJoe     PetscCall(PetscDrawSPReset(user->RhoDrawSP));
2618214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis_Rho, "Particles", "x", "rho"));
2628214e71cSJoe     PetscCall(PetscDrawSetSave(user->RhoDraw, "ex9_rho_spatial.png"));
2638214e71cSJoe 
2648214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "potential_monitor", 0, 0, 400, 300, &user->PotDraw));
2658214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->PotDraw));
2668214e71cSJoe     PetscCall(PetscDrawSPCreate(user->PotDraw, 10, &user->PotDrawSP));
2678214e71cSJoe     PetscCall(PetscDrawSPSetDimension(user->PotDrawSP, 1));
2688214e71cSJoe     PetscCall(PetscDrawSPGetAxis(user->PotDrawSP, &axis_Pot));
2698214e71cSJoe     PetscCall(PetscDrawSPReset(user->PotDrawSP));
2708214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis_Pot, "Particles", "x", "potential"));
2718214e71cSJoe     PetscCall(PetscDrawSetSave(user->PotDraw, "ex9_phi_spatial.png"));
2728214e71cSJoe   }
2738214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
2748214e71cSJoe }
2758214e71cSJoe 
2768214e71cSJoe static PetscErrorCode DestroyContext(AppCtx *user)
2778214e71cSJoe {
2788214e71cSJoe   PetscFunctionBeginUser;
2798214e71cSJoe   PetscCall(PetscDrawLGDestroy(&user->drawlg_ef));
2808214e71cSJoe   PetscCall(PetscDrawDestroy(&user->drawef));
2818214e71cSJoe   PetscCall(PetscDrawHGDestroy(&user->drawhgic_x));
2828214e71cSJoe   PetscCall(PetscDrawDestroy(&user->drawic_x));
2838214e71cSJoe   PetscCall(PetscDrawHGDestroy(&user->drawhgic_v));
2848214e71cSJoe   PetscCall(PetscDrawDestroy(&user->drawic_v));
2858214e71cSJoe   PetscCall(PetscDrawHGDestroy(&user->drawhgic_w));
2868214e71cSJoe   PetscCall(PetscDrawDestroy(&user->drawic_w));
2878214e71cSJoe   PetscCall(PetscDrawSPDestroy(&user->positionDrawSP));
2888214e71cSJoe   PetscCall(PetscDrawDestroy(&user->positionDraw));
2898214e71cSJoe 
2908214e71cSJoe   PetscCall(PetscDrawSPDestroy(&user->EDrawSP));
2918214e71cSJoe   PetscCall(PetscDrawDestroy(&user->EDraw));
2928214e71cSJoe   PetscCall(PetscDrawSPDestroy(&user->RhoDrawSP));
2938214e71cSJoe   PetscCall(PetscDrawDestroy(&user->RhoDraw));
2948214e71cSJoe   PetscCall(PetscDrawSPDestroy(&user->PotDrawSP));
2958214e71cSJoe   PetscCall(PetscDrawDestroy(&user->PotDraw));
2968214e71cSJoe 
2978214e71cSJoe   PetscCall(PetscBagDestroy(&user->bag));
2988214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
2998214e71cSJoe }
3008214e71cSJoe 
3018214e71cSJoe static PetscErrorCode CheckNonNegativeWeights(DM sw, AppCtx *user)
3028214e71cSJoe {
3038214e71cSJoe   const PetscScalar *w;
3048214e71cSJoe   PetscInt           Np;
3058214e71cSJoe 
3068214e71cSJoe   PetscFunctionBeginUser;
3078214e71cSJoe   if (!user->checkweights) PetscFunctionReturn(PETSC_SUCCESS);
3088214e71cSJoe   PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&w));
3098214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
3108214e71cSJoe   for (PetscInt p = 0; p < Np; ++p) PetscCheck(w[p] >= 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Particle %" PetscInt_FMT " has negative weight %g", p, w[p]);
3118214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&w));
3128214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
3138214e71cSJoe }
3148214e71cSJoe 
3158214e71cSJoe static PetscErrorCode computeParticleMoments(DM sw, PetscReal moments[3], AppCtx *user)
3168214e71cSJoe {
3178214e71cSJoe   DM                 dm;
3188214e71cSJoe   const PetscReal   *coords;
3198214e71cSJoe   const PetscScalar *w;
3208214e71cSJoe   PetscReal          mom[3] = {0.0, 0.0, 0.0};
3218214e71cSJoe   PetscInt           cell, cStart, cEnd, dim;
3228214e71cSJoe 
3238214e71cSJoe   PetscFunctionBeginUser;
3248214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
3258214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &dm));
3268214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
3278214e71cSJoe   PetscCall(DMSwarmSortGetAccess(sw));
3288214e71cSJoe   PetscCall(DMSwarmGetField(sw, "velocity", NULL, NULL, (void **)&coords));
3298214e71cSJoe   PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&w));
3308214e71cSJoe   for (cell = cStart; cell < cEnd; ++cell) {
3318214e71cSJoe     PetscInt *pidx;
3328214e71cSJoe     PetscInt  Np, p, d;
3338214e71cSJoe 
3348214e71cSJoe     PetscCall(DMSwarmSortGetPointsPerCell(sw, cell, &Np, &pidx));
3358214e71cSJoe     for (p = 0; p < Np; ++p) {
3368214e71cSJoe       const PetscInt   idx = pidx[p];
3378214e71cSJoe       const PetscReal *c   = &coords[idx * dim];
3388214e71cSJoe 
3398214e71cSJoe       mom[0] += PetscRealPart(w[idx]);
3408214e71cSJoe       mom[1] += PetscRealPart(w[idx]) * c[0];
3418214e71cSJoe       for (d = 0; d < dim; ++d) mom[2] += PetscRealPart(w[idx]) * c[d] * c[d];
3428214e71cSJoe       //if (w[idx] < 0. ) PetscPrintf(PETSC_COMM_WORLD, "error, negative weight %" PetscInt_FMT " \n", idx);
3438214e71cSJoe     }
3448214e71cSJoe     PetscCall(PetscFree(pidx));
3458214e71cSJoe   }
3468214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "velocity", NULL, NULL, (void **)&coords));
3478214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&w));
3488214e71cSJoe   PetscCall(DMSwarmSortRestoreAccess(sw));
349*6a210b70SBarry Smith   PetscCallMPI(MPIU_Allreduce(mom, moments, 3, MPIU_REAL, MPI_SUM, PetscObjectComm((PetscObject)sw)));
3508214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
3518214e71cSJoe }
3528214e71cSJoe 
3538214e71cSJoe static void f0_1(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
3548214e71cSJoe {
3558214e71cSJoe   f0[0] = u[0];
3568214e71cSJoe }
3578214e71cSJoe 
3588214e71cSJoe static void f0_x(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
3598214e71cSJoe {
3608214e71cSJoe   f0[0] = x[0] * u[0];
3618214e71cSJoe }
3628214e71cSJoe 
3638214e71cSJoe static void f0_r2(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
3648214e71cSJoe {
3658214e71cSJoe   PetscInt d;
3668214e71cSJoe 
3678214e71cSJoe   f0[0] = 0.0;
3688214e71cSJoe   for (d = 0; d < dim; ++d) f0[0] += PetscSqr(x[d]) * u[0];
3698214e71cSJoe }
3708214e71cSJoe 
3718214e71cSJoe static PetscErrorCode computeFEMMoments(DM dm, Vec u, PetscReal moments[3], AppCtx *user)
3728214e71cSJoe {
3738214e71cSJoe   PetscDS     prob;
3748214e71cSJoe   PetscScalar mom;
3758214e71cSJoe   PetscInt    field = 0;
3768214e71cSJoe 
3778214e71cSJoe   PetscFunctionBeginUser;
3788214e71cSJoe   PetscCall(DMGetDS(dm, &prob));
3798214e71cSJoe   PetscCall(PetscDSSetObjective(prob, field, &f0_1));
3808214e71cSJoe   PetscCall(DMPlexComputeIntegralFEM(dm, u, &mom, user));
3818214e71cSJoe   moments[0] = PetscRealPart(mom);
3828214e71cSJoe   PetscCall(PetscDSSetObjective(prob, field, &f0_x));
3838214e71cSJoe   PetscCall(DMPlexComputeIntegralFEM(dm, u, &mom, user));
3848214e71cSJoe   moments[1] = PetscRealPart(mom);
3858214e71cSJoe   PetscCall(PetscDSSetObjective(prob, field, &f0_r2));
3868214e71cSJoe   PetscCall(DMPlexComputeIntegralFEM(dm, u, &mom, user));
3878214e71cSJoe   moments[2] = PetscRealPart(mom);
3888214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
3898214e71cSJoe }
3908214e71cSJoe 
3918214e71cSJoe static PetscErrorCode MonitorEField(TS ts, PetscInt step, PetscReal t, Vec U, void *ctx)
3928214e71cSJoe {
3938214e71cSJoe   AppCtx    *user = (AppCtx *)ctx;
3948214e71cSJoe   DM         dm, sw;
3958214e71cSJoe   PetscReal *E;
3968214e71cSJoe   PetscReal  Enorm = 0., lgEnorm, lgEmax, sum = 0., Emax = 0., temp = 0., *weight, chargesum = 0.;
3978214e71cSJoe   PetscReal *x, *v;
3988214e71cSJoe   PetscInt  *species, dim, p, d, Np, cStart, cEnd;
3998214e71cSJoe   PetscReal  pmoments[3]; /* \int f, \int x f, \int r^2 f */
4008214e71cSJoe   PetscReal  fmoments[3]; /* \int \hat f, \int x \hat f, \int r^2 \hat f */
4018214e71cSJoe   Vec        rho;
4028214e71cSJoe 
4038214e71cSJoe   PetscFunctionBeginUser;
4048214e71cSJoe   if (step < 0) PetscFunctionReturn(PETSC_SUCCESS);
4058214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
4068214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &dm));
4078214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
4088214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
4098214e71cSJoe   PetscCall(DMSwarmSortGetAccess(sw));
4108214e71cSJoe   PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
4118214e71cSJoe   PetscCall(DMSwarmGetField(sw, "velocity", NULL, NULL, (void **)&v));
4128214e71cSJoe   PetscCall(DMSwarmGetField(sw, "E_field", NULL, NULL, (void **)&E));
4138214e71cSJoe   PetscCall(DMSwarmGetField(sw, "species", NULL, NULL, (void **)&species));
4148214e71cSJoe   PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&weight));
4158214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
4168214e71cSJoe 
4178214e71cSJoe   for (p = 0; p < Np; ++p) {
4188214e71cSJoe     for (d = 0; d < 1; ++d) {
4198214e71cSJoe       temp = PetscAbsReal(E[p * dim + d]);
4208214e71cSJoe       if (temp > Emax) Emax = temp;
4218214e71cSJoe     }
4228214e71cSJoe     Enorm += PetscSqrtReal(E[p * dim] * E[p * dim]);
4238214e71cSJoe     sum += E[p * dim];
4248214e71cSJoe     chargesum += user->charges[0] * weight[p];
4258214e71cSJoe   }
4268214e71cSJoe   lgEnorm = Enorm != 0 ? PetscLog10Real(Enorm) : -16.;
4278214e71cSJoe   lgEmax  = Emax != 0 ? PetscLog10Real(Emax) : -16.;
4288214e71cSJoe 
4298214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
4308214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "velocity", NULL, NULL, (void **)&v));
4318214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&weight));
4328214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "E_field", NULL, NULL, (void **)&E));
4338214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "species", NULL, NULL, (void **)&species));
4348214e71cSJoe 
4358214e71cSJoe   Parameter *param;
4368214e71cSJoe   PetscCall(PetscBagGetData(user->bag, (void **)&param));
4378214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "charges", &rho));
4388214e71cSJoe   if (user->em == EM_PRIMAL) {
4398214e71cSJoe     PetscCall(computeParticleMoments(sw, pmoments, user));
4408214e71cSJoe     PetscCall(computeFEMMoments(dm, rho, fmoments, user));
4418214e71cSJoe   } else if (user->em == EM_MIXED) {
4428214e71cSJoe     DM       potential_dm;
4438214e71cSJoe     IS       potential_IS;
4448214e71cSJoe     PetscInt fields = 1;
4458214e71cSJoe     PetscCall(DMCreateSubDM(dm, 1, &fields, &potential_IS, &potential_dm));
4468214e71cSJoe 
4478214e71cSJoe     PetscCall(computeParticleMoments(sw, pmoments, user));
4488214e71cSJoe     PetscCall(computeFEMMoments(potential_dm, rho, fmoments, user));
4498214e71cSJoe     PetscCall(DMDestroy(&potential_dm));
4508214e71cSJoe     PetscCall(ISDestroy(&potential_IS));
4518214e71cSJoe   }
4528214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "charges", &rho));
4538214e71cSJoe 
4548214e71cSJoe   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "%f\t%+e\t%e\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\n", (double)t, (double)sum, (double)Enorm, (double)lgEnorm, (double)Emax, (double)lgEmax, (double)chargesum, (double)pmoments[0], (double)pmoments[1], (double)pmoments[2], (double)fmoments[0], (double)fmoments[1], (double)fmoments[2]));
4558214e71cSJoe   PetscCall(PetscDrawLGAddPoint(user->drawlg_ef, &t, &lgEmax));
4568214e71cSJoe   PetscCall(PetscDrawLGDraw(user->drawlg_ef));
4578214e71cSJoe   PetscCall(PetscDrawSave(user->drawef));
4588214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
4598214e71cSJoe }
4608214e71cSJoe 
4618214e71cSJoe PetscErrorCode MonitorInitialConditions(TS ts, PetscInt step, PetscReal t, Vec U, void *ctx)
4628214e71cSJoe {
4638214e71cSJoe   AppCtx            *user = (AppCtx *)ctx;
4648214e71cSJoe   DM                 dm, sw;
4658214e71cSJoe   const PetscScalar *u;
4668214e71cSJoe   PetscReal         *weight, *pos, *vel;
4678214e71cSJoe   PetscInt           dim, p, Np, cStart, cEnd;
4688214e71cSJoe 
4698214e71cSJoe   PetscFunctionBegin;
4708214e71cSJoe   if (step < 0) PetscFunctionReturn(PETSC_SUCCESS); /* -1 indicates interpolated solution */
4718214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
4728214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &dm));
4738214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
4748214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
4758214e71cSJoe   PetscCall(DMSwarmSortGetAccess(sw));
4768214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
4778214e71cSJoe 
4788214e71cSJoe   if (step == 0) {
4798214e71cSJoe     PetscCall(PetscDrawHGReset(user->drawhgic_x));
4808214e71cSJoe     PetscCall(PetscDrawHGGetDraw(user->drawhgic_x, &user->drawic_x));
4818214e71cSJoe     PetscCall(PetscDrawClear(user->drawic_x));
4828214e71cSJoe     PetscCall(PetscDrawFlush(user->drawic_x));
4838214e71cSJoe 
4848214e71cSJoe     PetscCall(PetscDrawHGReset(user->drawhgic_v));
4858214e71cSJoe     PetscCall(PetscDrawHGGetDraw(user->drawhgic_v, &user->drawic_v));
4868214e71cSJoe     PetscCall(PetscDrawClear(user->drawic_v));
4878214e71cSJoe     PetscCall(PetscDrawFlush(user->drawic_v));
4888214e71cSJoe 
4898214e71cSJoe     PetscCall(PetscDrawHGReset(user->drawhgic_w));
4908214e71cSJoe     PetscCall(PetscDrawHGGetDraw(user->drawhgic_w, &user->drawic_w));
4918214e71cSJoe     PetscCall(PetscDrawClear(user->drawic_w));
4928214e71cSJoe     PetscCall(PetscDrawFlush(user->drawic_w));
4938214e71cSJoe 
4948214e71cSJoe     PetscCall(VecGetArrayRead(U, &u));
4958214e71cSJoe     PetscCall(DMSwarmGetField(sw, "velocity", NULL, NULL, (void **)&vel));
4968214e71cSJoe     PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&weight));
4978214e71cSJoe     PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&pos));
4988214e71cSJoe 
4998214e71cSJoe     PetscCall(VecGetLocalSize(U, &Np));
5008214e71cSJoe     Np /= dim * 2;
5018214e71cSJoe     for (p = 0; p < Np; ++p) {
5028214e71cSJoe       PetscCall(PetscDrawHGAddValue(user->drawhgic_x, pos[p * dim]));
5038214e71cSJoe       PetscCall(PetscDrawHGAddValue(user->drawhgic_v, vel[p * dim]));
5048214e71cSJoe       PetscCall(PetscDrawHGAddValue(user->drawhgic_w, weight[p]));
5058214e71cSJoe     }
5068214e71cSJoe 
5078214e71cSJoe     PetscCall(VecRestoreArrayRead(U, &u));
5088214e71cSJoe     PetscCall(PetscDrawHGDraw(user->drawhgic_x));
5098214e71cSJoe     PetscCall(PetscDrawHGSave(user->drawhgic_x));
5108214e71cSJoe 
5118214e71cSJoe     PetscCall(PetscDrawHGDraw(user->drawhgic_v));
5128214e71cSJoe     PetscCall(PetscDrawHGSave(user->drawhgic_v));
5138214e71cSJoe 
5148214e71cSJoe     PetscCall(PetscDrawHGDraw(user->drawhgic_w));
5158214e71cSJoe     PetscCall(PetscDrawHGSave(user->drawhgic_w));
5168214e71cSJoe 
5178214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&pos));
5188214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "velocity", NULL, NULL, (void **)&vel));
5198214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&weight));
5208214e71cSJoe   }
5218214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
5228214e71cSJoe }
5238214e71cSJoe 
5248214e71cSJoe static PetscErrorCode MonitorPositions_2D(TS ts, PetscInt step, PetscReal t, Vec U, void *ctx)
5258214e71cSJoe {
5268214e71cSJoe   AppCtx         *user = (AppCtx *)ctx;
5278214e71cSJoe   DM              dm, sw;
5288214e71cSJoe   PetscScalar    *x, *v, *weight;
5298214e71cSJoe   PetscReal       lower[3], upper[3], speed;
5308214e71cSJoe   const PetscInt *s;
5318214e71cSJoe   PetscInt        dim, cStart, cEnd, c;
5328214e71cSJoe 
5338214e71cSJoe   PetscFunctionBeginUser;
5348214e71cSJoe   if (step > 0 && step % user->ostep == 0) {
5358214e71cSJoe     PetscCall(TSGetDM(ts, &sw));
5368214e71cSJoe     PetscCall(DMSwarmGetCellDM(sw, &dm));
5378214e71cSJoe     PetscCall(DMGetDimension(dm, &dim));
5388214e71cSJoe     PetscCall(DMGetBoundingBox(dm, lower, upper));
5398214e71cSJoe     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
5408214e71cSJoe     PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
5418214e71cSJoe     PetscCall(DMSwarmGetField(sw, "velocity", NULL, NULL, (void **)&v));
5428214e71cSJoe     PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&weight));
5438214e71cSJoe     PetscCall(DMSwarmGetField(sw, "species", NULL, NULL, (void **)&s));
5448214e71cSJoe     PetscCall(DMSwarmSortGetAccess(sw));
5458214e71cSJoe     PetscCall(PetscDrawSPReset(user->positionDrawSP));
5468214e71cSJoe     PetscCall(PetscDrawSPSetLimits(user->positionDrawSP, lower[0], upper[0], lower[1], upper[1]));
5478214e71cSJoe     PetscCall(PetscDrawSPSetLimits(user->positionDrawSP, lower[0], upper[0], -12, 12));
5488214e71cSJoe     for (c = 0; c < cEnd - cStart; ++c) {
5498214e71cSJoe       PetscInt *pidx, Npc, q;
5508214e71cSJoe       PetscCall(DMSwarmSortGetPointsPerCell(sw, c, &Npc, &pidx));
5518214e71cSJoe       for (q = 0; q < Npc; ++q) {
5528214e71cSJoe         const PetscInt p = pidx[q];
5538214e71cSJoe         if (s[p] == 0) {
5548214e71cSJoe           speed = PetscSqrtReal(PetscSqr(v[p * dim]) + PetscSqr(v[p * dim + 1]));
5558214e71cSJoe           if (dim == 1 || user->fake_1D) {
5568214e71cSJoe             PetscCall(PetscDrawSPAddPointColorized(user->positionDrawSP, &x[p * dim], &v[p * dim], &speed));
5578214e71cSJoe           } else {
5588214e71cSJoe             PetscCall(PetscDrawSPAddPointColorized(user->positionDrawSP, &x[p * dim], &x[p * dim + 1], &speed));
5598214e71cSJoe           }
5608214e71cSJoe         } else if (s[p] == 1) {
5618214e71cSJoe           PetscCall(PetscDrawSPAddPoint(user->positionDrawSP, &x[p * dim], &v[p * dim]));
5628214e71cSJoe         }
5638214e71cSJoe       }
5648214e71cSJoe       PetscCall(PetscFree(pidx));
5658214e71cSJoe     }
5668214e71cSJoe     PetscCall(PetscDrawSPDraw(user->positionDrawSP, PETSC_TRUE));
5678214e71cSJoe     PetscCall(PetscDrawSave(user->positionDraw));
5688214e71cSJoe     PetscCall(DMSwarmSortRestoreAccess(sw));
5698214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
5708214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&weight));
5718214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "velocity", NULL, NULL, (void **)&v));
5728214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "species", NULL, NULL, (void **)&s));
5738214e71cSJoe   }
5748214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
5758214e71cSJoe }
5768214e71cSJoe 
5778214e71cSJoe static PetscErrorCode MonitorPoisson(TS ts, PetscInt step, PetscReal t, Vec U, void *ctx)
5788214e71cSJoe {
5798214e71cSJoe   AppCtx      *user = (AppCtx *)ctx;
5808214e71cSJoe   DM           dm, sw;
5818214e71cSJoe   PetscScalar *x, *E, *weight, *pot, *charges;
5828214e71cSJoe   PetscReal    lower[3], upper[3], xval;
5838214e71cSJoe   PetscInt     dim, cStart, cEnd, c;
5848214e71cSJoe 
5858214e71cSJoe   PetscFunctionBeginUser;
5868214e71cSJoe   if (step > 0 && step % user->ostep == 0) {
5878214e71cSJoe     PetscCall(TSGetDM(ts, &sw));
5888214e71cSJoe     PetscCall(DMSwarmGetCellDM(sw, &dm));
5898214e71cSJoe     PetscCall(DMGetDimension(dm, &dim));
5908214e71cSJoe     PetscCall(DMGetBoundingBox(dm, lower, upper));
5918214e71cSJoe     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
5928214e71cSJoe 
5938214e71cSJoe     PetscCall(PetscDrawSPReset(user->RhoDrawSP));
5948214e71cSJoe     PetscCall(PetscDrawSPReset(user->EDrawSP));
5958214e71cSJoe     PetscCall(PetscDrawSPReset(user->PotDrawSP));
5968214e71cSJoe     PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
5978214e71cSJoe     PetscCall(DMSwarmGetField(sw, "E_field", NULL, NULL, (void **)&E));
5988214e71cSJoe     PetscCall(DMSwarmGetField(sw, "potential", NULL, NULL, (void **)&pot));
5998214e71cSJoe     PetscCall(DMSwarmGetField(sw, "charges", NULL, NULL, (void **)&charges));
6008214e71cSJoe     PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&weight));
6018214e71cSJoe 
6028214e71cSJoe     PetscCall(DMSwarmSortGetAccess(sw));
6038214e71cSJoe     for (c = 0; c < cEnd - cStart; ++c) {
6048214e71cSJoe       PetscReal Esum = 0.0;
6058214e71cSJoe       PetscInt *pidx, Npc, q;
6068214e71cSJoe       PetscCall(DMSwarmSortGetPointsPerCell(sw, c, &Npc, &pidx));
6078214e71cSJoe       for (q = 0; q < Npc; ++q) {
6088214e71cSJoe         const PetscInt p = pidx[q];
6098214e71cSJoe         Esum += E[p * dim];
6108214e71cSJoe       }
6118214e71cSJoe       xval = (c + 0.5) * ((upper[0] - lower[0]) / (cEnd - cStart));
6128214e71cSJoe       PetscCall(PetscDrawSPAddPoint(user->EDrawSP, &xval, &Esum));
6138214e71cSJoe       PetscCall(PetscFree(pidx));
6148214e71cSJoe     }
6158214e71cSJoe     for (c = 0; c < (cEnd - cStart); ++c) {
6168214e71cSJoe       xval = (c + 0.5) * ((upper[0] - lower[0]) / (cEnd - cStart));
6178214e71cSJoe       PetscCall(PetscDrawSPAddPoint(user->RhoDrawSP, &xval, &charges[c]));
6188214e71cSJoe       PetscCall(PetscDrawSPAddPoint(user->PotDrawSP, &xval, &pot[c]));
6198214e71cSJoe     }
6208214e71cSJoe     PetscCall(PetscDrawSPDraw(user->RhoDrawSP, PETSC_TRUE));
6218214e71cSJoe     PetscCall(PetscDrawSave(user->RhoDraw));
6228214e71cSJoe     PetscCall(PetscDrawSPDraw(user->EDrawSP, PETSC_TRUE));
6238214e71cSJoe     PetscCall(PetscDrawSave(user->EDraw));
6248214e71cSJoe     PetscCall(PetscDrawSPDraw(user->PotDrawSP, PETSC_TRUE));
6258214e71cSJoe     PetscCall(PetscDrawSave(user->PotDraw));
6268214e71cSJoe     PetscCall(DMSwarmSortRestoreAccess(sw));
6278214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
6288214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "potential", NULL, NULL, (void **)&pot));
6298214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "charges", NULL, NULL, (void **)&charges));
6308214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&weight));
6318214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "E_field", NULL, NULL, (void **)&E));
6328214e71cSJoe   }
6338214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
6348214e71cSJoe }
6358214e71cSJoe 
6368214e71cSJoe static PetscErrorCode SetupParameters(MPI_Comm comm, AppCtx *ctx)
6378214e71cSJoe {
6388214e71cSJoe   PetscBag   bag;
6398214e71cSJoe   Parameter *p;
6408214e71cSJoe 
6418214e71cSJoe   PetscFunctionBeginUser;
6428214e71cSJoe   /* setup PETSc parameter bag */
6438214e71cSJoe   PetscCall(PetscBagGetData(ctx->bag, (void **)&p));
6448214e71cSJoe   PetscCall(PetscBagSetName(ctx->bag, "par", "Vlasov-Poisson Parameters"));
6458214e71cSJoe   bag = ctx->bag;
6468214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->v0, 1.0, "v0", "Velocity scale, m/s"));
6478214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->t0, 1.0, "t0", "Time scale, s"));
6488214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->x0, 1.0, "x0", "Space scale, m"));
6498214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->v0, 1.0, "phi0", "Potential scale, kg*m^2/A*s^3"));
6508214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->q0, 1.0, "q0", "Charge Scale, A*s"));
6518214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->m0, 1.0, "m0", "Mass Scale, kg"));
6528214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->epsi0, 1.0, "epsi0", "Permittivity of Free Space, kg"));
6538214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->kb, 1.0, "kb", "Boltzmann Constant, m^2 kg/s^2 K^1"));
6548214e71cSJoe 
6558214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->sigma, 1.0, "sigma", "Charge per unit area, C/m^3"));
6568214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->poissonNumber, 1.0, "poissonNumber", "Non-Dimensional Poisson Number"));
6578214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->vlasovNumber, 1.0, "vlasovNumber", "Non-Dimensional Vlasov Number"));
6588214e71cSJoe   PetscCall(PetscBagSetFromOptions(bag));
6598214e71cSJoe   {
6608214e71cSJoe     PetscViewer       viewer;
6618214e71cSJoe     PetscViewerFormat format;
6628214e71cSJoe     PetscBool         flg;
6638214e71cSJoe 
664648c30bcSBarry Smith     PetscCall(PetscOptionsCreateViewer(comm, NULL, NULL, "-param_view", &viewer, &format, &flg));
6658214e71cSJoe     if (flg) {
6668214e71cSJoe       PetscCall(PetscViewerPushFormat(viewer, format));
6678214e71cSJoe       PetscCall(PetscBagView(bag, viewer));
6688214e71cSJoe       PetscCall(PetscViewerFlush(viewer));
6698214e71cSJoe       PetscCall(PetscViewerPopFormat(viewer));
6708214e71cSJoe       PetscCall(PetscViewerDestroy(&viewer));
6718214e71cSJoe     }
6728214e71cSJoe   }
6738214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
6748214e71cSJoe }
6758214e71cSJoe 
6768214e71cSJoe static PetscErrorCode CreateMesh(MPI_Comm comm, AppCtx *user, DM *dm)
677d71ae5a4SJacob Faibussowitsch {
678b80bf5b1SJoe Pusztay   PetscFunctionBeginUser;
6799566063dSJacob Faibussowitsch   PetscCall(DMCreate(comm, dm));
6809566063dSJacob Faibussowitsch   PetscCall(DMSetType(*dm, DMPLEX));
6819566063dSJacob Faibussowitsch   PetscCall(DMSetFromOptions(*dm));
6829566063dSJacob Faibussowitsch   PetscCall(DMViewFromOptions(*dm, NULL, "-dm_view"));
6833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
684b80bf5b1SJoe Pusztay }
685b80bf5b1SJoe Pusztay 
6868214e71cSJoe static void ion_f0(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
6878214e71cSJoe {
6888214e71cSJoe   f0[0] = -constants[SIGMA];
6898214e71cSJoe }
6908214e71cSJoe 
691d71ae5a4SJacob Faibussowitsch static void laplacian_f1(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[])
692d71ae5a4SJacob Faibussowitsch {
693b80bf5b1SJoe Pusztay   PetscInt d;
694ad540459SPierre Jolivet   for (d = 0; d < dim; ++d) f1[d] = u_x[d];
695b80bf5b1SJoe Pusztay }
696b80bf5b1SJoe Pusztay 
6978214e71cSJoe static void laplacian_g3(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g3[])
698d71ae5a4SJacob Faibussowitsch {
699b80bf5b1SJoe Pusztay   PetscInt d;
700ad540459SPierre Jolivet   for (d = 0; d < dim; ++d) g3[d * dim + d] = 1.0;
701b80bf5b1SJoe Pusztay }
702b80bf5b1SJoe Pusztay 
7038214e71cSJoe static PetscErrorCode zero(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, void *ctx)
704d71ae5a4SJacob Faibussowitsch {
7058214e71cSJoe   *u = 0.0;
7068214e71cSJoe   return PETSC_SUCCESS;
707b80bf5b1SJoe Pusztay }
708b80bf5b1SJoe Pusztay 
709b80bf5b1SJoe Pusztay /*
7108214e71cSJoe    /  I   -grad\ / q \ = /0\
7118214e71cSJoe    \-div    0  / \phi/   \f/
712b80bf5b1SJoe Pusztay */
7138214e71cSJoe static void f0_q(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
714d71ae5a4SJacob Faibussowitsch {
7158214e71cSJoe   for (PetscInt d = 0; d < dim; ++d) f0[d] += u[uOff[0] + d];
7168214e71cSJoe }
7178214e71cSJoe 
7188214e71cSJoe static void f1_q(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[])
7198214e71cSJoe {
7208214e71cSJoe   for (PetscInt d = 0; d < dim; ++d) f1[d * dim + d] = u[uOff[1]];
7218214e71cSJoe }
7228214e71cSJoe 
7238214e71cSJoe static void f0_phi_backgroundCharge(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[])
7248214e71cSJoe {
7258214e71cSJoe   f0[0] += constants[SIGMA];
7268214e71cSJoe   for (PetscInt d = 0; d < dim; ++d) f0[0] += u_x[uOff_x[0] + d * dim + d];
7278214e71cSJoe }
7288214e71cSJoe 
7298214e71cSJoe /* Boundary residual. Dirichlet boundary for u means u_bdy=p*n */
7308214e71cSJoe static void g0_qq(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[])
7318214e71cSJoe {
7328214e71cSJoe   for (PetscInt d = 0; d < dim; ++d) g0[d * dim + d] = 1.0;
7338214e71cSJoe }
7348214e71cSJoe 
7358214e71cSJoe static void g2_qphi(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g2[])
7368214e71cSJoe {
7378214e71cSJoe   for (PetscInt d = 0; d < dim; ++d) g2[d * dim + d] = 1.0;
7388214e71cSJoe }
7398214e71cSJoe 
7408214e71cSJoe static void g1_phiq(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[], PetscInt numConstants, const PetscScalar constants[], PetscScalar g1[])
7418214e71cSJoe {
7428214e71cSJoe   for (PetscInt d = 0; d < dim; ++d) g1[d * dim + d] = 1.0;
7438214e71cSJoe }
7448214e71cSJoe 
7458214e71cSJoe static PetscErrorCode CreateFEM(DM dm, AppCtx *user)
7468214e71cSJoe {
7478214e71cSJoe   PetscFE   fephi, feq;
7488214e71cSJoe   PetscDS   ds;
7498214e71cSJoe   PetscBool simplex;
7508214e71cSJoe   PetscInt  dim;
7518214e71cSJoe 
7528214e71cSJoe   PetscFunctionBeginUser;
7538214e71cSJoe   PetscCall(DMGetDimension(dm, &dim));
7548214e71cSJoe   PetscCall(DMPlexIsSimplex(dm, &simplex));
7558214e71cSJoe   if (user->em == EM_MIXED) {
7568214e71cSJoe     DMLabel        label;
7578214e71cSJoe     const PetscInt id = 1;
7588214e71cSJoe 
7598214e71cSJoe     PetscCall(PetscFECreateDefault(PETSC_COMM_SELF, dim, dim, simplex, "field_", PETSC_DETERMINE, &feq));
7608214e71cSJoe     PetscCall(PetscObjectSetName((PetscObject)feq, "field"));
7618214e71cSJoe     PetscCall(PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, simplex, "potential_", PETSC_DETERMINE, &fephi));
7628214e71cSJoe     PetscCall(PetscObjectSetName((PetscObject)fephi, "potential"));
7638214e71cSJoe     PetscCall(PetscFECopyQuadrature(feq, fephi));
7648214e71cSJoe     PetscCall(DMSetField(dm, 0, NULL, (PetscObject)feq));
7658214e71cSJoe     PetscCall(DMSetField(dm, 1, NULL, (PetscObject)fephi));
7668214e71cSJoe     PetscCall(DMCreateDS(dm));
7678214e71cSJoe     PetscCall(PetscFEDestroy(&fephi));
7688214e71cSJoe     PetscCall(PetscFEDestroy(&feq));
7698214e71cSJoe 
7708214e71cSJoe     PetscCall(DMGetLabel(dm, "marker", &label));
7718214e71cSJoe     PetscCall(DMGetDS(dm, &ds));
7728214e71cSJoe 
7738214e71cSJoe     PetscCall(PetscDSSetResidual(ds, 0, f0_q, f1_q));
7748214e71cSJoe     PetscCall(PetscDSSetResidual(ds, 1, f0_phi_backgroundCharge, NULL));
7758214e71cSJoe     PetscCall(PetscDSSetJacobian(ds, 0, 0, g0_qq, NULL, NULL, NULL));
7768214e71cSJoe     PetscCall(PetscDSSetJacobian(ds, 0, 1, NULL, NULL, g2_qphi, NULL));
7778214e71cSJoe     PetscCall(PetscDSSetJacobian(ds, 1, 0, NULL, g1_phiq, NULL, NULL));
7788214e71cSJoe 
7798214e71cSJoe     PetscCall(DMAddBoundary(dm, DM_BC_ESSENTIAL, "wall", label, 1, &id, 0, 0, NULL, (void (*)(void))zero, NULL, NULL, NULL));
7808214e71cSJoe 
7818214e71cSJoe   } else if (user->em == EM_PRIMAL) {
7828214e71cSJoe     MatNullSpace nullsp;
7838214e71cSJoe     PetscCall(PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, simplex, NULL, PETSC_DETERMINE, &fephi));
7848214e71cSJoe     PetscCall(PetscObjectSetName((PetscObject)fephi, "potential"));
7858214e71cSJoe     PetscCall(DMSetField(dm, 0, NULL, (PetscObject)fephi));
7868214e71cSJoe     PetscCall(DMCreateDS(dm));
7878214e71cSJoe     PetscCall(DMGetDS(dm, &ds));
7888214e71cSJoe     PetscCall(PetscDSSetResidual(ds, 0, ion_f0, laplacian_f1));
7898214e71cSJoe     PetscCall(PetscDSSetJacobian(ds, 0, 0, NULL, NULL, NULL, laplacian_g3));
7908214e71cSJoe     PetscCall(MatNullSpaceCreate(PetscObjectComm((PetscObject)dm), PETSC_TRUE, 0, NULL, &nullsp));
7918214e71cSJoe     PetscCall(PetscObjectCompose((PetscObject)fephi, "nullspace", (PetscObject)nullsp));
7928214e71cSJoe     PetscCall(MatNullSpaceDestroy(&nullsp));
7938214e71cSJoe     PetscCall(PetscFEDestroy(&fephi));
7948214e71cSJoe   }
7958214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
7968214e71cSJoe }
7978214e71cSJoe 
7988214e71cSJoe static PetscErrorCode CreatePoisson(DM dm, AppCtx *user)
7998214e71cSJoe {
8008214e71cSJoe   SNES         snes;
8018214e71cSJoe   Mat          J;
8028214e71cSJoe   MatNullSpace nullSpace;
8038214e71cSJoe 
8048214e71cSJoe   PetscFunctionBeginUser;
8058214e71cSJoe   PetscCall(CreateFEM(dm, user));
8068214e71cSJoe   PetscCall(SNESCreate(PetscObjectComm((PetscObject)dm), &snes));
8078214e71cSJoe   PetscCall(SNESSetOptionsPrefix(snes, "em_"));
8088214e71cSJoe   PetscCall(SNESSetDM(snes, dm));
8098214e71cSJoe   PetscCall(DMPlexSetSNESLocalFEM(dm, PETSC_FALSE, user));
8108214e71cSJoe   PetscCall(SNESSetFromOptions(snes));
8118214e71cSJoe 
8128214e71cSJoe   PetscCall(DMCreateMatrix(dm, &J));
8138214e71cSJoe   PetscCall(MatNullSpaceCreate(PetscObjectComm((PetscObject)dm), PETSC_TRUE, 0, NULL, &nullSpace));
8148214e71cSJoe   PetscCall(MatSetNullSpace(J, nullSpace));
8158214e71cSJoe   PetscCall(MatNullSpaceDestroy(&nullSpace));
8168214e71cSJoe   PetscCall(SNESSetJacobian(snes, J, J, NULL, NULL));
8178214e71cSJoe   PetscCall(MatDestroy(&J));
8188214e71cSJoe   user->snes = snes;
8198214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
8208214e71cSJoe }
8218214e71cSJoe 
8228214e71cSJoe PetscErrorCode PetscPDFPertubedConstant2D(const PetscReal x[], const PetscReal dummy[], PetscReal p[])
8238214e71cSJoe {
8248214e71cSJoe   p[0] = (1 + 0.01 * PetscCosReal(0.5 * x[0])) / (2 * PETSC_PI);
8258214e71cSJoe   p[1] = (1 + 0.01 * PetscCosReal(0.5 * x[1])) / (2 * PETSC_PI);
8268214e71cSJoe   return PETSC_SUCCESS;
8278214e71cSJoe }
8288214e71cSJoe PetscErrorCode PetscPDFPertubedConstant1D(const PetscReal x[], const PetscReal dummy[], PetscReal p[])
8298214e71cSJoe {
8308214e71cSJoe   p[0] = (1. + 0.01 * PetscCosReal(0.5 * x[0])) / (2 * PETSC_PI);
8318214e71cSJoe   return PETSC_SUCCESS;
8328214e71cSJoe }
8338214e71cSJoe 
8348214e71cSJoe PetscErrorCode PetscPDFCosine1D(const PetscReal x[], const PetscReal scale[], PetscReal p[])
8358214e71cSJoe {
8368214e71cSJoe   const PetscReal alpha = scale ? scale[0] : 0.0;
8378214e71cSJoe   const PetscReal k     = scale ? scale[1] : 1.;
8388214e71cSJoe   p[0]                  = (1 + alpha * PetscCosReal(k * x[0]));
8398214e71cSJoe   return PETSC_SUCCESS;
8408214e71cSJoe }
8418214e71cSJoe 
8428214e71cSJoe PetscErrorCode PetscPDFCosine2D(const PetscReal x[], const PetscReal scale[], PetscReal p[])
8438214e71cSJoe {
8448214e71cSJoe   const PetscReal alpha = scale ? scale[0] : 0.;
8458214e71cSJoe   const PetscReal k     = scale ? scale[0] : 1.;
8468214e71cSJoe   p[0]                  = (1 + alpha * PetscCosReal(k * (x[0] + x[1])));
8478214e71cSJoe   return PETSC_SUCCESS;
8488214e71cSJoe }
8498214e71cSJoe 
8508214e71cSJoe PetscErrorCode PetscPDFCosine1D_TwoStream(const PetscReal x[], const PetscReal scale[], PetscReal p[])
8518214e71cSJoe {
8528214e71cSJoe   const PetscReal alpha = scale ? scale[0] : 0.0;
8538214e71cSJoe   const PetscReal k     = scale ? scale[1] : 1.;
8548214e71cSJoe   p[0]                  = (1. + alpha * PetscCosReal(k * x[0]));
8558214e71cSJoe   return PETSC_SUCCESS;
8568214e71cSJoe }
8578214e71cSJoe 
8588214e71cSJoe static PetscErrorCode InitializeParticles_PerturbedWeights(DM sw, AppCtx *user)
8598214e71cSJoe {
8608214e71cSJoe   DM           vdm, dm;
8618214e71cSJoe   PetscScalar *weight;
8628214e71cSJoe   PetscReal   *x, *v, vmin[3], vmax[3], gmin[3], gmax[3], xi0[3];
8638214e71cSJoe   PetscInt    *N, Ns, dim, *cellid, *species, Np, cStart, cEnd, Npc, n;
8648214e71cSJoe   PetscInt     Np_global, p, q, s, c, d, cv;
8658214e71cSJoe   PetscBool    flg;
8668214e71cSJoe   PetscMPIInt  size, rank;
8678214e71cSJoe   Parameter   *param;
8688214e71cSJoe 
8698214e71cSJoe   PetscFunctionBegin;
8708214e71cSJoe   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)sw), &size));
8718214e71cSJoe   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)sw), &rank));
8728214e71cSJoe   PetscOptionsBegin(PetscObjectComm((PetscObject)sw), "", "DMSwarm Options", "DMSWARM");
8738214e71cSJoe   PetscCall(DMSwarmGetNumSpecies(sw, &Ns));
8748214e71cSJoe   PetscCall(PetscOptionsInt("-dm_swarm_num_species", "The number of species", "DMSwarmSetNumSpecies", Ns, &Ns, &flg));
8758214e71cSJoe   if (flg) PetscCall(DMSwarmSetNumSpecies(sw, Ns));
8768214e71cSJoe   PetscCall(PetscCalloc1(Ns, &N));
8778214e71cSJoe   n = Ns;
8788214e71cSJoe   PetscCall(PetscOptionsIntArray("-dm_swarm_num_particles", "The target number of particles", "", N, &n, NULL));
8798214e71cSJoe   PetscOptionsEnd();
8808214e71cSJoe 
8818214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
8828214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &dm));
8838214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
8848214e71cSJoe 
8858214e71cSJoe   PetscCall(DMCreate(PETSC_COMM_SELF, &vdm));
8868214e71cSJoe   PetscCall(DMSetType(vdm, DMPLEX));
8878214e71cSJoe   PetscCall(DMPlexSetOptionsPrefix(vdm, "v"));
8888214e71cSJoe   PetscCall(DMSetFromOptions(vdm));
8898214e71cSJoe   PetscCall(DMViewFromOptions(vdm, NULL, "-vdm_view"));
8908214e71cSJoe 
8918214e71cSJoe   PetscInt vStart, vEnd;
8928214e71cSJoe   PetscCall(DMPlexGetHeightStratum(vdm, 0, &vStart, &vEnd));
8938214e71cSJoe   PetscCall(DMGetBoundingBox(vdm, vmin, vmax));
8948214e71cSJoe 
8958214e71cSJoe   PetscCall(DMGetBoundingBox(dm, gmin, gmax));
8968214e71cSJoe   PetscCall(PetscBagGetData(user->bag, (void **)&param));
8978214e71cSJoe   Np = (cEnd - cStart) * (vEnd - vStart);
8988214e71cSJoe   PetscCall(MPIU_Allreduce(&Np, &Np_global, 1, MPIU_INT, MPIU_SUM, PETSC_COMM_WORLD));
8998214e71cSJoe   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Global Np = %" PetscInt_FMT "\n", Np_global));
9008214e71cSJoe   PetscCall(DMSwarmSetLocalSizes(sw, Np, 0));
9018214e71cSJoe   Npc = Np / (cEnd - cStart);
9028214e71cSJoe   PetscCall(DMSwarmGetField(sw, DMSwarmPICField_cellid, NULL, NULL, (void **)&cellid));
9038214e71cSJoe   for (c = 0, p = 0; c < cEnd - cStart; ++c) {
9048214e71cSJoe     for (s = 0; s < Ns; ++s) {
9058214e71cSJoe       for (q = 0; q < Npc; ++q, ++p) cellid[p] = c;
9068214e71cSJoe     }
9078214e71cSJoe   }
9088214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_cellid, NULL, NULL, (void **)&cellid));
9098214e71cSJoe   PetscCall(PetscFree(N));
9108214e71cSJoe 
9118214e71cSJoe   PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
9128214e71cSJoe   PetscCall(DMSwarmGetField(sw, "velocity", NULL, NULL, (void **)&v));
9138214e71cSJoe   PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&weight));
9148214e71cSJoe   PetscCall(DMSwarmGetField(sw, "species", NULL, NULL, (void **)&species));
9158214e71cSJoe 
9168214e71cSJoe   PetscCall(DMSwarmSortGetAccess(sw));
9178214e71cSJoe   for (c = 0; c < cEnd - cStart; ++c) {
9188214e71cSJoe     const PetscInt cell = c + cStart;
9198214e71cSJoe     PetscInt      *pidx, Npc;
9208214e71cSJoe     PetscReal      centroid[3], volume;
9218214e71cSJoe 
9228214e71cSJoe     PetscCall(DMSwarmSortGetPointsPerCell(sw, c, &Npc, &pidx));
9238214e71cSJoe     PetscCall(DMPlexComputeCellGeometryFVM(dm, cell, &volume, centroid, NULL));
9248214e71cSJoe     for (q = 0; q < Npc; ++q) {
9258214e71cSJoe       const PetscInt p = pidx[q];
9268214e71cSJoe 
9278214e71cSJoe       for (d = 0; d < dim; ++d) {
9288214e71cSJoe         x[p * dim + d] = centroid[d];
9298214e71cSJoe         v[p * dim + d] = vmin[0] + (q + 0.5) * (vmax[0] - vmin[0]) / Npc;
9308214e71cSJoe         if (user->fake_1D && d > 0) v[p * dim + d] = 0;
9318214e71cSJoe       }
9328214e71cSJoe     }
9338214e71cSJoe     PetscCall(PetscFree(pidx));
9348214e71cSJoe   }
9358214e71cSJoe   PetscCall(DMGetCoordinatesLocalSetUp(vdm));
9368214e71cSJoe 
9378214e71cSJoe   /* Setup Quadrature for spatial and velocity weight calculations*/
9388214e71cSJoe   PetscQuadrature  quad_x;
9398214e71cSJoe   PetscInt         Nq_x;
9408214e71cSJoe   const PetscReal *wq_x, *xq_x;
9418214e71cSJoe   PetscReal       *xq_x_extended;
9428214e71cSJoe   PetscReal        weightsum = 0., totalcellweight = 0., *weight_x, *weight_v;
9438214e71cSJoe   PetscReal        scale[2] = {user->cosine_coefficients[0], user->cosine_coefficients[1]};
9448214e71cSJoe 
9458214e71cSJoe   PetscCall(PetscCalloc2(cEnd - cStart, &weight_x, Np, &weight_v));
9468214e71cSJoe   if (user->fake_1D) PetscCall(PetscDTGaussTensorQuadrature(1, 1, 5, -1.0, 1.0, &quad_x));
9478214e71cSJoe   else PetscCall(PetscDTGaussTensorQuadrature(dim, 1, 5, -1.0, 1.0, &quad_x));
9488214e71cSJoe   PetscCall(PetscQuadratureGetData(quad_x, NULL, NULL, &Nq_x, &xq_x, &wq_x));
9498214e71cSJoe   if (user->fake_1D) {
9508214e71cSJoe     PetscCall(PetscCalloc1(Nq_x * dim, &xq_x_extended));
9518214e71cSJoe     for (PetscInt i = 0; i < Nq_x; ++i) xq_x_extended[i * dim] = xq_x[i];
9528214e71cSJoe   }
9538214e71cSJoe   /* Integrate the density function to get the weights of particles in each cell */
9548214e71cSJoe   for (d = 0; d < dim; ++d) xi0[d] = -1.0;
9558214e71cSJoe   for (c = cStart; c < cEnd; ++c) {
9568214e71cSJoe     PetscReal          v0_x[3], J_x[9], invJ_x[9], detJ_x, xr_x[3], den_x;
9578214e71cSJoe     PetscInt          *pidx, Npc, q;
9588214e71cSJoe     PetscInt           Ncx;
9598214e71cSJoe     const PetscScalar *array_x;
9608214e71cSJoe     PetscScalar       *coords_x = NULL;
9618214e71cSJoe     PetscBool          isDGx;
9628214e71cSJoe     weight_x[c] = 0.;
9638214e71cSJoe 
9648214e71cSJoe     PetscCall(DMPlexGetCellCoordinates(dm, c, &isDGx, &Ncx, &array_x, &coords_x));
9658214e71cSJoe     PetscCall(DMSwarmSortGetPointsPerCell(sw, c, &Npc, &pidx));
9668214e71cSJoe     PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, v0_x, J_x, invJ_x, &detJ_x));
9678214e71cSJoe     for (q = 0; q < Nq_x; ++q) {
9688214e71cSJoe       /*Transform quadrature points from ref space to real space (0,12.5664)*/
9698214e71cSJoe       if (user->fake_1D) CoordinatesRefToReal(dim, dim, xi0, v0_x, J_x, &xq_x_extended[q * dim], xr_x);
9708214e71cSJoe       else CoordinatesRefToReal(dim, dim, xi0, v0_x, J_x, &xq_x[q * dim], xr_x);
9718214e71cSJoe 
9728214e71cSJoe       /*Transform quadrature points from real space to ideal real space (0, 2PI/k)*/
9738214e71cSJoe       if (user->fake_1D) {
9748214e71cSJoe         if (user->twostream) PetscCall(PetscPDFCosine1D_TwoStream(xr_x, scale, &den_x));
9758214e71cSJoe         else PetscCall(PetscPDFCosine1D(xr_x, scale, &den_x));
9768214e71cSJoe         detJ_x = J_x[0];
9778214e71cSJoe       } else PetscCall(PetscPDFCosine2D(xr_x, scale, &den_x));
9788214e71cSJoe       /*We have to transform the quadrature weights as well*/
9798214e71cSJoe       weight_x[c] += den_x * (wq_x[q] * detJ_x);
9808214e71cSJoe     }
9818214e71cSJoe     // Get the cell numbering for consistent output between sequential and distributed tests
9828214e71cSJoe     IS              globalOrdering;
9838214e71cSJoe     const PetscInt *ordering;
9848214e71cSJoe     PetscCall(DMPlexGetCellNumbering(dm, &globalOrdering));
9858214e71cSJoe     PetscCall(ISGetIndices(globalOrdering, &ordering));
9868214e71cSJoe     PetscCall(PetscSynchronizedPrintf(PETSC_COMM_WORLD, "c:%" PetscInt_FMT " [x_a,x_b] = %1.15f,%1.15f -> cell weight = %1.15f\n", ordering[c], (double)PetscRealPart(coords_x[0]), (double)PetscRealPart(coords_x[2]), (double)weight_x[c]));
9878214e71cSJoe     PetscCall(ISRestoreIndices(globalOrdering, &ordering));
9888214e71cSJoe     totalcellweight += weight_x[c];
9898214e71cSJoe     // Confirm the number of particles per spatial cell conforms to the size of the velocity grid
9908214e71cSJoe     PetscCheck(Npc == vEnd - vStart, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of particles %" PetscInt_FMT " in cell (rank %d/%d) != %" PetscInt_FMT " number of velocity vertices", Npc, rank, size, vEnd - vStart);
9918214e71cSJoe 
9928214e71cSJoe     /* Set weights to be gaussian in velocity cells (using exact solution) */
9938214e71cSJoe     for (cv = 0; cv < vEnd - vStart; ++cv) {
9948214e71cSJoe       PetscInt           Nc;
9958214e71cSJoe       const PetscScalar *array_v;
9968214e71cSJoe       PetscScalar       *coords_v = NULL;
9978214e71cSJoe       PetscBool          isDG;
9988214e71cSJoe       PetscCall(DMPlexGetCellCoordinates(vdm, cv, &isDG, &Nc, &array_v, &coords_v));
9998214e71cSJoe 
10008214e71cSJoe       const PetscInt p = pidx[cv];
10018214e71cSJoe       // Two stream function from 1/2pi v^2 e^(-v^2/2)
10028214e71cSJoe       if (user->twostream)
10038214e71cSJoe         weight_v[p] = 1. / (PetscSqrtReal(2 * PETSC_PI)) * (((coords_v[0] * PetscExpReal(-PetscSqr(coords_v[0]) / 2.)) - (coords_v[1] * PetscExpReal(-PetscSqr(coords_v[1]) / 2.)))) - 0.5 * PetscErfReal(coords_v[0] / PetscSqrtReal(2.)) + 0.5 * (PetscErfReal(coords_v[1] / PetscSqrtReal(2.)));
10048214e71cSJoe       else weight_v[p] = 0.5 * (PetscErfReal(coords_v[1] / PetscSqrtReal(2.)) - PetscErfReal(coords_v[0] / PetscSqrtReal(2.)));
10058214e71cSJoe 
10068214e71cSJoe       weight[p] = user->totalWeight * weight_v[p] * weight_x[c];
10078214e71cSJoe       if (weight[p] > 1.) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "weights: %g, %g, %g\n", user->totalWeight, weight_v[p], weight_x[c]));
10088214e71cSJoe       //PetscPrintf(PETSC_COMM_WORLD, "particle %"PetscInt_FMT": %g, weight_v: %g weight_x: %g\n", p, weight[p], weight_v[p], weight_x[p]);
10098214e71cSJoe       weightsum += weight[p];
10108214e71cSJoe 
10118214e71cSJoe       PetscCall(DMPlexRestoreCellCoordinates(vdm, cv, &isDG, &Nc, &array_v, &coords_v));
10128214e71cSJoe     }
10138214e71cSJoe     PetscCall(DMPlexRestoreCellCoordinates(dm, c, &isDGx, &Ncx, &array_x, &coords_x));
10148214e71cSJoe     PetscCall(PetscFree(pidx));
10158214e71cSJoe   }
10168214e71cSJoe   PetscCall(PetscSynchronizedFlush(PETSC_COMM_WORLD, PETSC_STDOUT));
10178214e71cSJoe   PetscReal global_cellweight, global_weightsum;
10188214e71cSJoe   PetscCall(MPIU_Allreduce(&totalcellweight, &global_cellweight, 1, MPIU_REAL, MPIU_SUM, PETSC_COMM_WORLD));
10198214e71cSJoe   PetscCall(MPIU_Allreduce(&weightsum, &global_weightsum, 1, MPIU_REAL, MPIU_SUM, PETSC_COMM_WORLD));
10208214e71cSJoe   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "particle weight sum = %1.10f cell weight sum = %1.10f\n", (double)global_cellweight, (double)global_weightsum));
10218214e71cSJoe   if (user->fake_1D) PetscCall(PetscFree(xq_x_extended));
10228214e71cSJoe   PetscCall(PetscFree2(weight_x, weight_v));
10238214e71cSJoe   PetscCall(PetscQuadratureDestroy(&quad_x));
10248214e71cSJoe   PetscCall(DMSwarmSortRestoreAccess(sw));
10258214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
10268214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&weight));
10278214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "species", NULL, NULL, (void **)&species));
10288214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "velocity", NULL, NULL, (void **)&v));
10298214e71cSJoe   PetscCall(DMDestroy(&vdm));
10308214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
10318214e71cSJoe }
10328214e71cSJoe 
10338214e71cSJoe static PetscErrorCode InitializeConstants(DM sw, AppCtx *user)
10348214e71cSJoe {
10358214e71cSJoe   DM         dm;
10368214e71cSJoe   PetscInt  *species;
10378214e71cSJoe   PetscReal *weight, totalCharge = 0., totalWeight = 0., gmin[3], gmax[3], global_charge, global_weight;
10388214e71cSJoe   PetscInt   Np, dim;
10398214e71cSJoe 
10408214e71cSJoe   PetscFunctionBegin;
10418214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &dm));
10428214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
10438214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
10448214e71cSJoe   PetscCall(DMGetBoundingBox(dm, gmin, gmax));
10458214e71cSJoe   PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&weight));
10468214e71cSJoe   PetscCall(DMSwarmGetField(sw, "species", NULL, NULL, (void **)&species));
10478214e71cSJoe   for (PetscInt p = 0; p < Np; ++p) {
10488214e71cSJoe     totalWeight += weight[p];
10498214e71cSJoe     totalCharge += user->charges[species[p]] * weight[p];
10508214e71cSJoe   }
10518214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&weight));
10528214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "species", NULL, NULL, (void **)&species));
10538214e71cSJoe   {
10548214e71cSJoe     Parameter *param;
10558214e71cSJoe     PetscReal  Area;
10568214e71cSJoe 
10578214e71cSJoe     PetscCall(PetscBagGetData(user->bag, (void **)&param));
10588214e71cSJoe     switch (dim) {
10598214e71cSJoe     case 1:
10608214e71cSJoe       Area = (gmax[0] - gmin[0]);
10618214e71cSJoe       break;
10628214e71cSJoe     case 2:
10638214e71cSJoe       if (user->fake_1D) {
10648214e71cSJoe         Area = (gmax[0] - gmin[0]);
10658214e71cSJoe       } else {
10668214e71cSJoe         Area = (gmax[0] - gmin[0]) * (gmax[1] - gmin[1]);
10678214e71cSJoe       }
10688214e71cSJoe       break;
10698214e71cSJoe     case 3:
10708214e71cSJoe       Area = (gmax[0] - gmin[0]) * (gmax[1] - gmin[1]) * (gmax[2] - gmin[2]);
10718214e71cSJoe       break;
10728214e71cSJoe     default:
10738214e71cSJoe       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Dimension %" PetscInt_FMT " not supported", dim);
10748214e71cSJoe     }
10758214e71cSJoe     PetscCall(MPIU_Allreduce(&totalWeight, &global_weight, 1, MPIU_REAL, MPIU_SUM, PETSC_COMM_WORLD));
10768214e71cSJoe     PetscCall(MPIU_Allreduce(&totalCharge, &global_charge, 1, MPIU_REAL, MPIU_SUM, PETSC_COMM_WORLD));
10778214e71cSJoe     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "dim = %" PetscInt_FMT "\ttotalWeight = %f, user->charges[species[0]] = %f\ttotalCharge = %f, Total Area = %f\n", dim, (double)global_weight, (double)user->charges[0], (double)global_charge, (double)Area));
10788214e71cSJoe     param->sigma = PetscAbsReal(global_charge / (Area));
10798214e71cSJoe 
10808214e71cSJoe     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "sigma: %g\n", (double)param->sigma));
10818214e71cSJoe     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "(x0,v0,t0,m0,q0,phi0): (%e, %e, %e, %e, %e, %e) - (P, V) = (%e, %e)\n", (double)param->x0, (double)param->v0, (double)param->t0, (double)param->m0, (double)param->q0, (double)param->phi0, (double)param->poissonNumber,
10828214e71cSJoe                           (double)param->vlasovNumber));
10838214e71cSJoe   }
10848214e71cSJoe   /* Setup Constants */
10858214e71cSJoe   {
10868214e71cSJoe     PetscDS    ds;
10878214e71cSJoe     Parameter *param;
10888214e71cSJoe     PetscCall(PetscBagGetData(user->bag, (void **)&param));
10898214e71cSJoe     PetscScalar constants[NUM_CONSTANTS];
10908214e71cSJoe     constants[SIGMA]   = param->sigma;
10918214e71cSJoe     constants[V0]      = param->v0;
10928214e71cSJoe     constants[T0]      = param->t0;
10938214e71cSJoe     constants[X0]      = param->x0;
10948214e71cSJoe     constants[M0]      = param->m0;
10958214e71cSJoe     constants[Q0]      = param->q0;
10968214e71cSJoe     constants[PHI0]    = param->phi0;
10978214e71cSJoe     constants[POISSON] = param->poissonNumber;
10988214e71cSJoe     constants[VLASOV]  = param->vlasovNumber;
10998214e71cSJoe     PetscCall(DMGetDS(dm, &ds));
11008214e71cSJoe     PetscCall(PetscDSSetConstants(ds, NUM_CONSTANTS, constants));
11018214e71cSJoe   }
11028214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
11038214e71cSJoe }
11048214e71cSJoe 
11058214e71cSJoe static PetscErrorCode InitializeVelocities_Fake1D(DM sw, AppCtx *user)
11068214e71cSJoe {
11078214e71cSJoe   DM         dm;
11088214e71cSJoe   PetscReal *v;
11098214e71cSJoe   PetscInt  *species, cStart, cEnd;
11108214e71cSJoe   PetscInt   dim, Np;
11118214e71cSJoe 
11128214e71cSJoe   PetscFunctionBegin;
11138214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
11148214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
11158214e71cSJoe   PetscCall(DMSwarmGetField(sw, "velocity", NULL, NULL, (void **)&v));
11168214e71cSJoe   PetscCall(DMSwarmGetField(sw, "species", NULL, NULL, (void **)&species));
11178214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &dm));
11188214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
11198214e71cSJoe   PetscRandom rnd;
11208214e71cSJoe   PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)sw), &rnd));
11218214e71cSJoe   PetscCall(PetscRandomSetInterval(rnd, 0, 1.));
11228214e71cSJoe   PetscCall(PetscRandomSetFromOptions(rnd));
11238214e71cSJoe 
11248214e71cSJoe   for (PetscInt p = 0; p < Np; ++p) {
11258214e71cSJoe     PetscReal a[3] = {0., 0., 0.}, vel[3] = {0., 0., 0.};
11268214e71cSJoe 
11278214e71cSJoe     PetscCall(PetscRandomGetValueReal(rnd, &a[0]));
11288214e71cSJoe     if (user->perturbed_weights) {
11298214e71cSJoe       PetscCall(PetscPDFSampleConstant1D(a, NULL, vel));
11308214e71cSJoe     } else {
11318214e71cSJoe       PetscCall(PetscPDFSampleGaussian1D(a, NULL, vel));
11328214e71cSJoe     }
11338214e71cSJoe     v[p * dim] = vel[0];
11348214e71cSJoe   }
11358214e71cSJoe   PetscCall(PetscRandomDestroy(&rnd));
11368214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "velocity", NULL, NULL, (void **)&v));
11378214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "species", NULL, NULL, (void **)&species));
11388214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
11398214e71cSJoe }
11408214e71cSJoe 
11418214e71cSJoe static PetscErrorCode CreateSwarm(DM dm, AppCtx *user, DM *sw)
11428214e71cSJoe {
11438214e71cSJoe   PetscReal v0[2] = {1., 0.};
11448214e71cSJoe   PetscInt  dim;
1145b80bf5b1SJoe Pusztay 
1146b80bf5b1SJoe Pusztay   PetscFunctionBeginUser;
11479566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
11489566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), sw));
11499566063dSJacob Faibussowitsch   PetscCall(DMSetType(*sw, DMSWARM));
11509566063dSJacob Faibussowitsch   PetscCall(DMSetDimension(*sw, dim));
11519566063dSJacob Faibussowitsch   PetscCall(DMSwarmSetType(*sw, DMSWARM_PIC));
11529566063dSJacob Faibussowitsch   PetscCall(DMSwarmSetCellDM(*sw, dm));
11539566063dSJacob Faibussowitsch   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "w_q", 1, PETSC_SCALAR));
11548214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "velocity", dim, PETSC_REAL));
11558214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "species", 1, PETSC_INT));
11568214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "initCoordinates", dim, PETSC_REAL));
11578214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "initVelocity", dim, PETSC_REAL));
11588214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "E_field", dim, PETSC_REAL));
11598214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "potential", dim, PETSC_REAL));
11608214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "charges", dim, PETSC_REAL));
11619566063dSJacob Faibussowitsch   PetscCall(DMSwarmFinalizeFieldRegister(*sw));
11628214e71cSJoe   PetscCall(DMSetApplicationContext(*sw, user));
11639566063dSJacob Faibussowitsch   PetscCall(DMSetFromOptions(*sw));
11648214e71cSJoe   user->swarm = *sw;
11658214e71cSJoe   if (user->perturbed_weights) {
11668214e71cSJoe     PetscCall(InitializeParticles_PerturbedWeights(*sw, user));
1167b80bf5b1SJoe Pusztay   } else {
11688214e71cSJoe     PetscCall(DMSwarmComputeLocalSizeFromOptions(*sw));
11698214e71cSJoe     PetscCall(DMSwarmInitializeCoordinates(*sw));
11708214e71cSJoe     if (user->fake_1D) {
11718214e71cSJoe       PetscCall(InitializeVelocities_Fake1D(*sw, user));
11729371c9d4SSatish Balay     } else {
11738214e71cSJoe       PetscCall(DMSwarmInitializeVelocitiesFromOptions(*sw, v0));
1174b80bf5b1SJoe Pusztay     }
1175b80bf5b1SJoe Pusztay   }
11769566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetName((PetscObject)*sw, "Particles"));
11779566063dSJacob Faibussowitsch   PetscCall(DMViewFromOptions(*sw, NULL, "-sw_view"));
11788214e71cSJoe   {
11798214e71cSJoe     Vec gc, gc0, gv, gv0;
11808214e71cSJoe 
11818214e71cSJoe     PetscCall(DMSwarmCreateGlobalVectorFromField(*sw, DMSwarmPICField_coor, &gc));
11828214e71cSJoe     PetscCall(DMSwarmCreateGlobalVectorFromField(*sw, "initCoordinates", &gc0));
11838214e71cSJoe     PetscCall(VecCopy(gc, gc0));
11848214e71cSJoe     PetscCall(VecViewFromOptions(gc, NULL, "-ic_x_view"));
11858214e71cSJoe     PetscCall(DMSwarmDestroyGlobalVectorFromField(*sw, DMSwarmPICField_coor, &gc));
11868214e71cSJoe     PetscCall(DMSwarmDestroyGlobalVectorFromField(*sw, "initCoordinates", &gc0));
11878214e71cSJoe     PetscCall(DMSwarmCreateGlobalVectorFromField(*sw, "velocity", &gv));
11888214e71cSJoe     PetscCall(DMSwarmCreateGlobalVectorFromField(*sw, "initVelocity", &gv0));
11898214e71cSJoe     PetscCall(VecCopy(gv, gv0));
11908214e71cSJoe     PetscCall(VecViewFromOptions(gv, NULL, "-ic_v_view"));
11918214e71cSJoe     PetscCall(DMSwarmDestroyGlobalVectorFromField(*sw, "velocity", &gv));
11928214e71cSJoe     PetscCall(DMSwarmDestroyGlobalVectorFromField(*sw, "initVelocity", &gv0));
11938214e71cSJoe   }
11943ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1195b80bf5b1SJoe Pusztay }
1196b80bf5b1SJoe Pusztay 
11978214e71cSJoe static PetscErrorCode ComputeFieldAtParticles_Coulomb(SNES snes, DM sw, PetscReal E[])
1198d71ae5a4SJacob Faibussowitsch {
11998214e71cSJoe   AppCtx     *user;
12008214e71cSJoe   PetscReal  *coords;
12018214e71cSJoe   PetscInt   *species, dim, Np, Ns;
12028214e71cSJoe   PetscMPIInt size;
12038214e71cSJoe 
12048214e71cSJoe   PetscFunctionBegin;
12058214e71cSJoe   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)snes), &size));
12068214e71cSJoe   PetscCheck(size == 1, PetscObjectComm((PetscObject)snes), PETSC_ERR_SUP, "Coulomb code only works in serial");
12078214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
12088214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
12098214e71cSJoe   PetscCall(DMSwarmGetNumSpecies(sw, &Ns));
12108214e71cSJoe   PetscCall(DMGetApplicationContext(sw, (void *)&user));
12118214e71cSJoe 
12128214e71cSJoe   PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&coords));
12138214e71cSJoe   PetscCall(DMSwarmGetField(sw, "species", NULL, NULL, (void **)&species));
12148214e71cSJoe   for (PetscInt p = 0; p < Np; ++p) {
12158214e71cSJoe     PetscReal *pcoord = &coords[p * dim];
12168214e71cSJoe     PetscReal  pE[3]  = {0., 0., 0.};
12178214e71cSJoe 
12188214e71cSJoe     /* Calculate field at particle p due to particle q */
12198214e71cSJoe     for (PetscInt q = 0; q < Np; ++q) {
12208214e71cSJoe       PetscReal *qcoord = &coords[q * dim];
12218214e71cSJoe       PetscReal  rpq[3], r, r3, q_q;
12228214e71cSJoe 
12238214e71cSJoe       if (p == q) continue;
12248214e71cSJoe       q_q = user->charges[species[q]] * 1.;
12258214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) rpq[d] = pcoord[d] - qcoord[d];
12268214e71cSJoe       r = DMPlex_NormD_Internal(dim, rpq);
12278214e71cSJoe       if (r < PETSC_SQRT_MACHINE_EPSILON) continue;
12288214e71cSJoe       r3 = PetscPowRealInt(r, 3);
12298214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) pE[d] += q_q * rpq[d] / r3;
12308214e71cSJoe     }
12318214e71cSJoe     for (PetscInt d = 0; d < dim; ++d) E[p * dim + d] = pE[d];
12328214e71cSJoe   }
12338214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "species", NULL, NULL, (void **)&species));
12348214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&coords));
12358214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
12368214e71cSJoe }
12378214e71cSJoe 
12388214e71cSJoe static PetscErrorCode ComputeFieldAtParticles_Primal(SNES snes, DM sw, PetscReal E[])
12398214e71cSJoe {
1240b80bf5b1SJoe Pusztay   DM              dm;
12418214e71cSJoe   AppCtx         *user;
12428214e71cSJoe   PetscDS         ds;
12438214e71cSJoe   PetscFE         fe;
12448214e71cSJoe   Mat             M_p, M;
12458214e71cSJoe   Vec             phi, locPhi, rho, f;
12468214e71cSJoe   PetscReal      *coords;
12478214e71cSJoe   PetscInt        dim, cStart, cEnd, Np;
12488214e71cSJoe   PetscQuadrature q;
12498214e71cSJoe 
12508214e71cSJoe   PetscFunctionBegin;
12518214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
12528214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
12538214e71cSJoe   PetscCall(DMGetApplicationContext(sw, (void *)&user));
12548214e71cSJoe 
12558214e71cSJoe   KSP         ksp;
12568214e71cSJoe   Vec         rho0;
12578214e71cSJoe   char        oldField[PETSC_MAX_PATH_LEN];
12588214e71cSJoe   const char *tmp;
12598214e71cSJoe 
12608214e71cSJoe   /* Create the charges rho */
12618214e71cSJoe   PetscCall(SNESGetDM(snes, &dm));
12628214e71cSJoe   PetscCall(DMSwarmVectorGetField(sw, &tmp));
12638214e71cSJoe   PetscCall(PetscStrncpy(oldField, tmp, PETSC_MAX_PATH_LEN));
12648214e71cSJoe   PetscCall(DMSwarmVectorDefineField(sw, "w_q"));
12658214e71cSJoe   PetscCall(DMCreateMassMatrix(sw, dm, &M_p));
12668214e71cSJoe   PetscCall(DMSwarmVectorDefineField(sw, oldField));
12678214e71cSJoe 
12688214e71cSJoe   PetscCall(DMCreateMassMatrix(dm, dm, &M));
12698214e71cSJoe   PetscCall(DMGetGlobalVector(dm, &rho0));
12708214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)rho0, "Charge density (rho0) from Primal Compute"));
12718214e71cSJoe   PetscCall(DMGetGlobalVector(dm, &rho));
12728214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)rho, "rho"));
12738214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "w_q", &f));
12748214e71cSJoe 
12758214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)f, "particle weight"));
12768214e71cSJoe   PetscCall(MatMultTranspose(M_p, f, rho));
12778214e71cSJoe   PetscCall(MatViewFromOptions(M_p, NULL, "-mp_view"));
12788214e71cSJoe   PetscCall(MatViewFromOptions(M, NULL, "-m_view"));
12798214e71cSJoe   PetscCall(VecViewFromOptions(f, NULL, "-weights_view"));
12808214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "w_q", &f));
12818214e71cSJoe 
12828214e71cSJoe   PetscCall(KSPCreate(PetscObjectComm((PetscObject)dm), &ksp));
12838214e71cSJoe   PetscCall(KSPSetOptionsPrefix(ksp, "em_proj_"));
12848214e71cSJoe   PetscCall(KSPSetOperators(ksp, M, M));
12858214e71cSJoe   PetscCall(KSPSetFromOptions(ksp));
12868214e71cSJoe   PetscCall(KSPSolve(ksp, rho, rho0));
12878214e71cSJoe   PetscCall(VecViewFromOptions(rho0, NULL, "-rho0_view"));
12888214e71cSJoe 
12898214e71cSJoe   PetscInt           rhosize;
12908214e71cSJoe   PetscReal         *charges;
12918214e71cSJoe   const PetscScalar *rho_vals;
12928214e71cSJoe   PetscCall(DMSwarmGetField(sw, "charges", NULL, NULL, (void **)&charges));
12938214e71cSJoe   PetscCall(VecGetLocalSize(rho0, &rhosize));
12948214e71cSJoe   PetscCall(VecGetArrayRead(rho0, &rho_vals));
12958214e71cSJoe   for (PetscInt c = 0; c < rhosize; ++c) charges[c] = rho_vals[c];
12968214e71cSJoe   PetscCall(VecRestoreArrayRead(rho0, &rho_vals));
12978214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "charges", NULL, NULL, (void **)&charges));
12988214e71cSJoe 
12998214e71cSJoe   PetscCall(VecScale(rho, -1.0));
13008214e71cSJoe 
13018214e71cSJoe   PetscCall(VecViewFromOptions(rho0, NULL, "-rho0_view"));
13028214e71cSJoe   PetscCall(VecViewFromOptions(rho, NULL, "-rho_view"));
13038214e71cSJoe   PetscCall(DMRestoreGlobalVector(dm, &rho0));
13048214e71cSJoe   PetscCall(KSPDestroy(&ksp));
13058214e71cSJoe   PetscCall(MatDestroy(&M_p));
13068214e71cSJoe   PetscCall(MatDestroy(&M));
13078214e71cSJoe 
13088214e71cSJoe   PetscCall(DMGetGlobalVector(dm, &phi));
13098214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)phi, "potential"));
13108214e71cSJoe   PetscCall(VecSet(phi, 0.0));
13118214e71cSJoe   PetscCall(SNESSolve(snes, rho, phi));
13128214e71cSJoe   PetscCall(DMRestoreGlobalVector(dm, &rho));
13138214e71cSJoe   PetscCall(VecViewFromOptions(phi, NULL, "-phi_view"));
13148214e71cSJoe 
13158214e71cSJoe   PetscInt           phisize;
13168214e71cSJoe   PetscReal         *pot;
13178214e71cSJoe   const PetscScalar *phi_vals;
13188214e71cSJoe   PetscCall(DMSwarmGetField(sw, "potential", NULL, NULL, (void **)&pot));
13198214e71cSJoe   PetscCall(VecGetLocalSize(phi, &phisize));
13208214e71cSJoe   PetscCall(VecGetArrayRead(phi, &phi_vals));
13218214e71cSJoe   for (PetscInt c = 0; c < phisize; ++c) pot[c] = phi_vals[c];
13228214e71cSJoe   PetscCall(VecRestoreArrayRead(phi, &phi_vals));
13238214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "potential", NULL, NULL, (void **)&pot));
13248214e71cSJoe 
13258214e71cSJoe   PetscCall(DMGetLocalVector(dm, &locPhi));
13268214e71cSJoe   PetscCall(DMGlobalToLocalBegin(dm, phi, INSERT_VALUES, locPhi));
13278214e71cSJoe   PetscCall(DMGlobalToLocalEnd(dm, phi, INSERT_VALUES, locPhi));
13288214e71cSJoe   PetscCall(DMRestoreGlobalVector(dm, &phi));
13298214e71cSJoe 
13308214e71cSJoe   PetscCall(DMGetDS(dm, &ds));
13318214e71cSJoe   PetscCall(PetscDSGetDiscretization(ds, 0, (PetscObject *)&fe));
13328214e71cSJoe   PetscCall(DMSwarmSortGetAccess(sw));
13338214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
13348214e71cSJoe   PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&coords));
13358214e71cSJoe 
13368214e71cSJoe   for (PetscInt c = cStart; c < cEnd; ++c) {
13378214e71cSJoe     PetscTabulation tab;
13388214e71cSJoe     PetscScalar    *clPhi = NULL;
13398214e71cSJoe     PetscReal      *pcoord, *refcoord;
13408214e71cSJoe     PetscReal       v[3], J[9], invJ[9], detJ;
13418214e71cSJoe     PetscInt       *points;
13428214e71cSJoe     PetscInt        Ncp;
13438214e71cSJoe 
13448214e71cSJoe     PetscCall(DMSwarmSortGetPointsPerCell(sw, c, &Ncp, &points));
13458214e71cSJoe     PetscCall(DMGetWorkArray(dm, Ncp * dim, MPIU_REAL, &pcoord));
13468214e71cSJoe     PetscCall(DMGetWorkArray(dm, Ncp * dim, MPIU_REAL, &refcoord));
13478214e71cSJoe     for (PetscInt cp = 0; cp < Ncp; ++cp)
13488214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) pcoord[cp * dim + d] = coords[points[cp] * dim + d];
13498214e71cSJoe     PetscCall(DMPlexCoordinatesToReference(dm, c, Ncp, pcoord, refcoord));
13508214e71cSJoe     PetscCall(PetscFECreateTabulation(fe, 1, Ncp, refcoord, 1, &tab));
13518214e71cSJoe     PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, v, J, invJ, &detJ));
13528214e71cSJoe     PetscCall(DMPlexVecGetClosure(dm, NULL, locPhi, c, NULL, &clPhi));
13538214e71cSJoe     for (PetscInt cp = 0; cp < Ncp; ++cp) {
13548214e71cSJoe       const PetscReal *basisDer = tab->T[1];
13558214e71cSJoe       const PetscInt   p        = points[cp];
13568214e71cSJoe 
13578214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) E[p * dim + d] = 0.;
13588214e71cSJoe       PetscCall(PetscFEGetQuadrature(fe, &q));
13598214e71cSJoe       PetscCall(PetscFEFreeInterpolateGradient_Static(fe, basisDer, clPhi, dim, invJ, NULL, cp, &E[p * dim]));
13608214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) {
13618214e71cSJoe         E[p * dim + d] *= -1.0;
13628214e71cSJoe         if (user->fake_1D && d > 0) E[p * dim + d] = 0;
13638214e71cSJoe       }
13648214e71cSJoe     }
13658214e71cSJoe     PetscCall(DMPlexVecRestoreClosure(dm, NULL, locPhi, c, NULL, &clPhi));
13668214e71cSJoe     PetscCall(DMRestoreWorkArray(dm, Ncp * dim, MPIU_REAL, &pcoord));
13678214e71cSJoe     PetscCall(DMRestoreWorkArray(dm, Ncp * dim, MPIU_REAL, &refcoord));
13688214e71cSJoe     PetscCall(PetscTabulationDestroy(&tab));
13698214e71cSJoe     PetscCall(PetscFree(points));
13708214e71cSJoe   }
13718214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&coords));
13728214e71cSJoe   PetscCall(DMSwarmSortRestoreAccess(sw));
13738214e71cSJoe   PetscCall(DMRestoreLocalVector(dm, &locPhi));
13748214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
13758214e71cSJoe }
13768214e71cSJoe 
13778214e71cSJoe static PetscErrorCode ComputeFieldAtParticles_Mixed(SNES snes, DM sw, PetscReal E[])
13788214e71cSJoe {
13798214e71cSJoe   AppCtx         *user;
13808214e71cSJoe   DM              dm, potential_dm;
13818214e71cSJoe   KSP             ksp;
13828214e71cSJoe   IS              potential_IS;
13838214e71cSJoe   PetscDS         ds;
13848214e71cSJoe   PetscFE         fe;
13858214e71cSJoe   PetscFEGeom     feGeometry;
13868214e71cSJoe   Mat             M_p, M;
13878214e71cSJoe   Vec             phi, locPhi, rho, f, temp_rho, rho0;
13888214e71cSJoe   PetscQuadrature q;
13898214e71cSJoe   PetscReal      *coords, *pot;
13908214e71cSJoe   PetscInt        dim, cStart, cEnd, Np, fields = 1;
13918214e71cSJoe   char            oldField[PETSC_MAX_PATH_LEN];
13928214e71cSJoe   const char     *tmp;
13938214e71cSJoe 
13948214e71cSJoe   PetscFunctionBegin;
13958214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
13968214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
13978214e71cSJoe   PetscCall(DMGetApplicationContext(sw, &user));
13988214e71cSJoe 
13998214e71cSJoe   /* Create the charges rho */
14008214e71cSJoe   PetscCall(SNESGetDM(snes, &dm));
14018214e71cSJoe   PetscCall(DMGetGlobalVector(dm, &rho));
14028214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)rho, "rho"));
14038214e71cSJoe 
14048214e71cSJoe   PetscCall(DMCreateSubDM(dm, 1, &fields, &potential_IS, &potential_dm));
14058214e71cSJoe 
14068214e71cSJoe   PetscCall(DMSwarmVectorGetField(sw, &tmp));
14078214e71cSJoe   PetscCall(PetscStrncpy(oldField, tmp, PETSC_MAX_PATH_LEN));
14088214e71cSJoe   PetscCall(DMSwarmVectorDefineField(sw, "w_q"));
14098214e71cSJoe   PetscCall(DMCreateMassMatrix(sw, potential_dm, &M_p));
14108214e71cSJoe   PetscCall(DMSwarmVectorDefineField(sw, oldField));
14118214e71cSJoe 
14128214e71cSJoe   PetscCall(DMCreateMassMatrix(potential_dm, potential_dm, &M));
14138214e71cSJoe   PetscCall(MatViewFromOptions(M_p, NULL, "-mp_view"));
14148214e71cSJoe   PetscCall(MatViewFromOptions(M, NULL, "-m_view"));
14158214e71cSJoe   PetscCall(DMGetGlobalVector(potential_dm, &temp_rho));
14168214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)temp_rho, "Mf"));
14178214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "w_q", &f));
14188214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)f, "particle weight"));
14198214e71cSJoe   PetscCall(VecViewFromOptions(f, NULL, "-weights_view"));
14208214e71cSJoe   PetscCall(MatMultTranspose(M_p, f, temp_rho));
14218214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "w_q", &f));
14228214e71cSJoe   PetscCall(DMGetGlobalVector(potential_dm, &rho0));
14238214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)rho0, "Charge density (rho0) from Mixed Compute"));
14248214e71cSJoe 
14258214e71cSJoe   PetscCall(KSPCreate(PetscObjectComm((PetscObject)dm), &ksp));
14268214e71cSJoe   PetscCall(KSPSetOptionsPrefix(ksp, "em_proj"));
14278214e71cSJoe   PetscCall(KSPSetOperators(ksp, M, M));
14288214e71cSJoe   PetscCall(KSPSetFromOptions(ksp));
14298214e71cSJoe   PetscCall(KSPSolve(ksp, temp_rho, rho0));
14308214e71cSJoe   PetscCall(VecViewFromOptions(rho0, NULL, "-rho0_view"));
14318214e71cSJoe 
14328214e71cSJoe   PetscInt           rhosize;
14338214e71cSJoe   PetscReal         *charges;
14348214e71cSJoe   const PetscScalar *rho_vals;
14358214e71cSJoe   Parameter         *param;
14368214e71cSJoe   PetscCall(PetscBagGetData(user->bag, (void **)&param));
14378214e71cSJoe   PetscCall(DMSwarmGetField(sw, "charges", NULL, NULL, (void **)&charges));
14388214e71cSJoe   PetscCall(VecGetLocalSize(rho0, &rhosize));
14398214e71cSJoe 
14408214e71cSJoe   /* Integral over reference element is size 1.  Reference element area is 4.  Scale rho0 by 1/4 because the basis function is 1/4 */
14418214e71cSJoe   PetscCall(VecScale(rho0, 0.25));
14428214e71cSJoe   PetscCall(VecGetArrayRead(rho0, &rho_vals));
14438214e71cSJoe   for (PetscInt c = 0; c < rhosize; ++c) charges[c] = rho_vals[c];
14448214e71cSJoe   PetscCall(VecRestoreArrayRead(rho0, &rho_vals));
14458214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "charges", NULL, NULL, (void **)&charges));
14468214e71cSJoe 
14478214e71cSJoe   PetscCall(VecISCopy(rho, potential_IS, SCATTER_FORWARD, temp_rho));
14488214e71cSJoe   PetscCall(VecScale(rho, 0.25));
14498214e71cSJoe   PetscCall(VecViewFromOptions(rho0, NULL, "-rho0_view"));
14508214e71cSJoe   PetscCall(VecViewFromOptions(temp_rho, NULL, "-temprho_view"));
14518214e71cSJoe   PetscCall(VecViewFromOptions(rho, NULL, "-rho_view"));
14528214e71cSJoe   PetscCall(DMRestoreGlobalVector(potential_dm, &temp_rho));
14538214e71cSJoe   PetscCall(DMRestoreGlobalVector(potential_dm, &rho0));
14548214e71cSJoe 
14558214e71cSJoe   PetscCall(MatDestroy(&M_p));
14568214e71cSJoe   PetscCall(MatDestroy(&M));
14578214e71cSJoe   PetscCall(KSPDestroy(&ksp));
14588214e71cSJoe   PetscCall(DMDestroy(&potential_dm));
14598214e71cSJoe   PetscCall(ISDestroy(&potential_IS));
14608214e71cSJoe 
14618214e71cSJoe   PetscCall(DMGetGlobalVector(dm, &phi));
14628214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)phi, "potential"));
14638214e71cSJoe   PetscCall(VecSet(phi, 0.0));
14648214e71cSJoe   PetscCall(SNESSolve(snes, rho, phi));
14658214e71cSJoe   PetscCall(DMRestoreGlobalVector(dm, &rho));
14668214e71cSJoe 
14678214e71cSJoe   PetscInt           phisize;
14688214e71cSJoe   const PetscScalar *phi_vals;
14698214e71cSJoe   PetscCall(DMSwarmGetField(sw, "potential", NULL, NULL, (void **)&pot));
14708214e71cSJoe   PetscCall(VecGetLocalSize(phi, &phisize));
14718214e71cSJoe   PetscCall(VecViewFromOptions(phi, NULL, "-phi_view"));
14728214e71cSJoe   PetscCall(VecGetArrayRead(phi, &phi_vals));
14738214e71cSJoe   for (PetscInt c = 0; c < phisize; ++c) pot[c] = phi_vals[c];
14748214e71cSJoe   PetscCall(VecRestoreArrayRead(phi, &phi_vals));
14758214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "potential", NULL, NULL, (void **)&pot));
14768214e71cSJoe 
14778214e71cSJoe   PetscCall(DMGetLocalVector(dm, &locPhi));
14788214e71cSJoe   PetscCall(DMGlobalToLocalBegin(dm, phi, INSERT_VALUES, locPhi));
14798214e71cSJoe   PetscCall(DMGlobalToLocalEnd(dm, phi, INSERT_VALUES, locPhi));
14808214e71cSJoe   PetscCall(DMRestoreGlobalVector(dm, &phi));
14818214e71cSJoe 
14828214e71cSJoe   PetscCall(DMGetDS(dm, &ds));
14838214e71cSJoe   PetscCall(PetscDSGetDiscretization(ds, 0, (PetscObject *)&fe));
14848214e71cSJoe   PetscCall(DMSwarmSortGetAccess(sw));
14858214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
14868214e71cSJoe   PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&coords));
14878214e71cSJoe   PetscCall(PetscFEGetQuadrature(fe, &q));
14888214e71cSJoe   PetscCall(PetscFECreateCellGeometry(fe, q, &feGeometry));
14898214e71cSJoe   for (PetscInt c = cStart; c < cEnd; ++c) {
14908214e71cSJoe     PetscTabulation tab;
14918214e71cSJoe     PetscScalar    *clPhi = NULL;
14928214e71cSJoe     PetscReal      *pcoord, *refcoord;
14938214e71cSJoe     PetscInt       *points;
14948214e71cSJoe     PetscInt        Ncp;
14958214e71cSJoe 
14968214e71cSJoe     PetscCall(DMSwarmSortGetPointsPerCell(sw, c, &Ncp, &points));
14978214e71cSJoe     PetscCall(DMGetWorkArray(dm, Ncp * dim, MPIU_REAL, &pcoord));
14988214e71cSJoe     PetscCall(DMGetWorkArray(dm, Ncp * dim, MPIU_REAL, &refcoord));
14998214e71cSJoe     for (PetscInt cp = 0; cp < Ncp; ++cp)
15008214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) pcoord[cp * dim + d] = coords[points[cp] * dim + d];
15018214e71cSJoe     PetscCall(DMPlexCoordinatesToReference(dm, c, Ncp, pcoord, refcoord));
15028214e71cSJoe     PetscCall(PetscFECreateTabulation(fe, 1, Ncp, refcoord, 1, &tab));
15038214e71cSJoe     PetscCall(DMPlexComputeCellGeometryFEM(dm, c, q, feGeometry.v, feGeometry.J, feGeometry.invJ, feGeometry.detJ));
15048214e71cSJoe     PetscCall(DMPlexVecGetClosure(dm, NULL, locPhi, c, NULL, &clPhi));
15058214e71cSJoe 
15068214e71cSJoe     for (PetscInt cp = 0; cp < Ncp; ++cp) {
15078214e71cSJoe       const PetscInt p = points[cp];
15088214e71cSJoe 
15098214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) E[p * dim + d] = 0.;
15108214e71cSJoe       PetscCall(PetscFEInterpolateAtPoints_Static(fe, tab, clPhi, &feGeometry, cp, &E[p * dim]));
15118214e71cSJoe       PetscCall(PetscFEPushforward(fe, &feGeometry, 1, &E[p * dim]));
15128214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) {
15138214e71cSJoe         E[p * dim + d] *= -2.0;
15148214e71cSJoe         if (user->fake_1D && d > 0) E[p * dim + d] = 0;
15158214e71cSJoe       }
15168214e71cSJoe     }
15178214e71cSJoe     PetscCall(DMPlexVecRestoreClosure(dm, NULL, locPhi, c, NULL, &clPhi));
15188214e71cSJoe     PetscCall(DMRestoreWorkArray(dm, Ncp * dim, MPIU_REAL, &pcoord));
15198214e71cSJoe     PetscCall(DMRestoreWorkArray(dm, Ncp * dim, MPIU_REAL, &refcoord));
15208214e71cSJoe     PetscCall(PetscTabulationDestroy(&tab));
15218214e71cSJoe     PetscCall(PetscFree(points));
15228214e71cSJoe   }
15238214e71cSJoe   PetscCall(PetscFEDestroyCellGeometry(fe, &feGeometry));
15248214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&coords));
15258214e71cSJoe   PetscCall(DMSwarmSortRestoreAccess(sw));
15268214e71cSJoe   PetscCall(DMRestoreLocalVector(dm, &locPhi));
15278214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
15288214e71cSJoe }
15298214e71cSJoe 
15308214e71cSJoe static PetscErrorCode ComputeFieldAtParticles(SNES snes, DM sw, PetscReal E[])
15318214e71cSJoe {
15328214e71cSJoe   AppCtx  *ctx;
15338214e71cSJoe   PetscInt dim, Np;
15348214e71cSJoe 
15358214e71cSJoe   PetscFunctionBegin;
15368214e71cSJoe   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
15378214e71cSJoe   PetscValidHeaderSpecific(sw, DM_CLASSID, 2);
15388214e71cSJoe   PetscAssertPointer(E, 3);
15398214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
15408214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
15418214e71cSJoe   PetscCall(DMGetApplicationContext(sw, &ctx));
15428214e71cSJoe   PetscCall(PetscArrayzero(E, Np * dim));
15438214e71cSJoe 
15448214e71cSJoe   switch (ctx->em) {
15458214e71cSJoe   case EM_PRIMAL:
15468214e71cSJoe     PetscCall(ComputeFieldAtParticles_Primal(snes, sw, E));
15478214e71cSJoe     break;
15488214e71cSJoe   case EM_COULOMB:
15498214e71cSJoe     PetscCall(ComputeFieldAtParticles_Coulomb(snes, sw, E));
15508214e71cSJoe     break;
15518214e71cSJoe   case EM_MIXED:
15528214e71cSJoe     PetscCall(ComputeFieldAtParticles_Mixed(snes, sw, E));
15538214e71cSJoe     break;
15548214e71cSJoe   case EM_NONE:
15558214e71cSJoe     break;
15568214e71cSJoe   default:
15578214e71cSJoe     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No solver for electrostatic model %s", EMTypes[ctx->em]);
15588214e71cSJoe   }
15598214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
15608214e71cSJoe }
15618214e71cSJoe 
15628214e71cSJoe static PetscErrorCode RHSFunction(TS ts, PetscReal t, Vec U, Vec G, void *ctx)
15638214e71cSJoe {
15648214e71cSJoe   DM                 sw;
15658214e71cSJoe   SNES               snes = ((AppCtx *)ctx)->snes;
15668214e71cSJoe   const PetscReal   *coords, *vel;
15678214e71cSJoe   const PetscScalar *u;
15688214e71cSJoe   PetscScalar       *g;
15698214e71cSJoe   PetscReal         *E, m_p = 1., q_p = -1.;
15708214e71cSJoe   PetscInt           dim, d, Np, p;
1571b80bf5b1SJoe Pusztay 
1572b80bf5b1SJoe Pusztay   PetscFunctionBeginUser;
15738214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
15748214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
15758214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
15768214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initVelocity", NULL, NULL, (void **)&vel));
15778214e71cSJoe   PetscCall(DMSwarmGetField(sw, "E_field", NULL, NULL, (void **)&E));
15788214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
15798214e71cSJoe   PetscCall(VecGetArrayRead(U, &u));
15808214e71cSJoe   PetscCall(VecGetArray(G, &g));
15818214e71cSJoe 
15828214e71cSJoe   PetscCall(ComputeFieldAtParticles(snes, sw, E));
15838214e71cSJoe 
15848214e71cSJoe   Np /= 2 * dim;
15858214e71cSJoe   for (p = 0; p < Np; ++p) {
15868214e71cSJoe     for (d = 0; d < dim; ++d) {
15878214e71cSJoe       g[(p * 2 + 0) * dim + d] = u[(p * 2 + 1) * dim + d];
15888214e71cSJoe       g[(p * 2 + 1) * dim + d] = q_p * E[p * dim + d] / m_p;
15898214e71cSJoe     }
15908214e71cSJoe   }
15918214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
15928214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initVelocity", NULL, NULL, (void **)&vel));
15938214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "E_field", NULL, NULL, (void **)&E));
15948214e71cSJoe   PetscCall(VecRestoreArrayRead(U, &u));
15958214e71cSJoe   PetscCall(VecRestoreArray(G, &g));
15968214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
15978214e71cSJoe }
15988214e71cSJoe 
15998214e71cSJoe /* J_{ij} = dF_i/dx_j
16008214e71cSJoe    J_p = (  0   1)
16018214e71cSJoe          (-w^2  0)
16028214e71cSJoe    TODO Now there is another term with w^2 from the electric field. I think we will need to invert the operator.
16038214e71cSJoe         Perhaps we can approximate the Jacobian using only the cellwise P-P gradient from Coulomb
16048214e71cSJoe */
16058214e71cSJoe static PetscErrorCode RHSJacobian(TS ts, PetscReal t, Vec U, Mat J, Mat P, void *ctx)
16068214e71cSJoe {
16078214e71cSJoe   DM               sw;
16088214e71cSJoe   const PetscReal *coords, *vel;
16098214e71cSJoe   PetscInt         dim, d, Np, p, rStart;
16108214e71cSJoe 
16118214e71cSJoe   PetscFunctionBeginUser;
16128214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
16138214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
16148214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
16158214e71cSJoe   PetscCall(MatGetOwnershipRange(J, &rStart, NULL));
16168214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
16178214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initVelocity", NULL, NULL, (void **)&vel));
16188214e71cSJoe   Np /= 2 * dim;
16198214e71cSJoe   for (p = 0; p < Np; ++p) {
16208214e71cSJoe     const PetscReal x0      = coords[p * dim + 0];
16218214e71cSJoe     const PetscReal vy0     = vel[p * dim + 1];
16228214e71cSJoe     const PetscReal omega   = vy0 / x0;
16238214e71cSJoe     PetscScalar     vals[4] = {0., 1., -PetscSqr(omega), 0.};
16248214e71cSJoe 
16258214e71cSJoe     for (d = 0; d < dim; ++d) {
16268214e71cSJoe       const PetscInt rows[2] = {(p * 2 + 0) * dim + d + rStart, (p * 2 + 1) * dim + d + rStart};
16278214e71cSJoe       PetscCall(MatSetValues(J, 2, rows, 2, rows, vals, INSERT_VALUES));
16288214e71cSJoe     }
16298214e71cSJoe   }
16308214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
16318214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initVelocity", NULL, NULL, (void **)&vel));
16328214e71cSJoe   PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
16338214e71cSJoe   PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
16348214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
16358214e71cSJoe }
16368214e71cSJoe 
16378214e71cSJoe static PetscErrorCode RHSFunctionX(TS ts, PetscReal t, Vec V, Vec Xres, void *ctx)
16388214e71cSJoe {
16398214e71cSJoe   AppCtx            *user = (AppCtx *)ctx;
16408214e71cSJoe   DM                 sw;
16418214e71cSJoe   const PetscScalar *v;
16428214e71cSJoe   PetscScalar       *xres;
16438214e71cSJoe   PetscInt           Np, p, d, dim;
16448214e71cSJoe 
16458214e71cSJoe   PetscFunctionBeginUser;
16468214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
16478214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
16488214e71cSJoe   PetscCall(VecGetLocalSize(Xres, &Np));
16499566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(V, &v));
16508214e71cSJoe   PetscCall(VecGetArray(Xres, &xres));
1651b80bf5b1SJoe Pusztay   Np /= dim;
1652b80bf5b1SJoe Pusztay   for (p = 0; p < Np; ++p) {
16538214e71cSJoe     for (d = 0; d < dim; ++d) {
16548214e71cSJoe       xres[p * dim + d] = v[p * dim + d];
16558214e71cSJoe       if (user->fake_1D && d > 0) xres[p * dim + d] = 0;
16568214e71cSJoe     }
1657b80bf5b1SJoe Pusztay   }
16589566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(V, &v));
16598214e71cSJoe   PetscCall(VecRestoreArray(Xres, &xres));
16603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1661b80bf5b1SJoe Pusztay }
1662b80bf5b1SJoe Pusztay 
16638214e71cSJoe static PetscErrorCode RHSFunctionV(TS ts, PetscReal t, Vec X, Vec Vres, void *ctx)
16648214e71cSJoe {
16658214e71cSJoe   DM                 sw;
16668214e71cSJoe   AppCtx            *user = (AppCtx *)ctx;
16678214e71cSJoe   SNES               snes = ((AppCtx *)ctx)->snes;
16688214e71cSJoe   const PetscScalar *x;
16698214e71cSJoe   const PetscReal   *coords, *vel;
16708214e71cSJoe   PetscReal         *E, m_p, q_p;
16718214e71cSJoe   PetscScalar       *vres;
16728214e71cSJoe   PetscInt           Np, p, dim, d;
16738214e71cSJoe   Parameter         *param;
16748214e71cSJoe 
16758214e71cSJoe   PetscFunctionBeginUser;
16768214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
16778214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
16788214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
16798214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initVelocity", NULL, NULL, (void **)&vel));
16808214e71cSJoe   PetscCall(DMSwarmGetField(sw, "E_field", NULL, NULL, (void **)&E));
16818214e71cSJoe   PetscCall(PetscBagGetData(user->bag, (void **)&param));
16828214e71cSJoe   m_p = user->masses[0] * param->m0;
16838214e71cSJoe   q_p = user->charges[0] * param->q0;
16848214e71cSJoe   PetscCall(VecGetLocalSize(Vres, &Np));
16858214e71cSJoe   PetscCall(VecGetArrayRead(X, &x));
16868214e71cSJoe   PetscCall(VecGetArray(Vres, &vres));
16878214e71cSJoe   PetscCheck(dim == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Dimension must be 2");
16888214e71cSJoe   PetscCall(ComputeFieldAtParticles(snes, sw, E));
16898214e71cSJoe 
16908214e71cSJoe   Np /= dim;
16918214e71cSJoe   for (p = 0; p < Np; ++p) {
16928214e71cSJoe     for (d = 0; d < dim; ++d) {
16938214e71cSJoe       vres[p * dim + d] = q_p * E[p * dim + d] / m_p;
16948214e71cSJoe       if (user->fake_1D && d > 0) vres[p * dim + d] = 0.;
16958214e71cSJoe     }
16968214e71cSJoe   }
16978214e71cSJoe   PetscCall(VecRestoreArrayRead(X, &x));
16988214e71cSJoe   /*
16998214e71cSJoe     Syncrhonized, ordered output for parallel/sequential test cases.
17008214e71cSJoe     In the 1D (on the 2D mesh) case, every y component should be zero.
17018214e71cSJoe   */
17028214e71cSJoe   if (user->checkVRes) {
17038214e71cSJoe     PetscBool pr = user->checkVRes > 1 ? PETSC_TRUE : PETSC_FALSE;
17048214e71cSJoe     PetscInt  step;
17058214e71cSJoe 
17068214e71cSJoe     PetscCall(TSGetStepNumber(ts, &step));
17078214e71cSJoe     if (pr) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "step: %" PetscInt_FMT "\n", step));
17088214e71cSJoe     for (PetscInt p = 0; p < Np; ++p) {
17098214e71cSJoe       if (pr) PetscCall(PetscSynchronizedPrintf(PETSC_COMM_WORLD, "Residual: %.12g %.12g\n", (double)PetscRealPart(vres[p * dim + 0]), (double)PetscRealPart(vres[p * dim + 1])));
17108214e71cSJoe       PetscCheck(PetscAbsScalar(vres[p * dim + 1]) < PETSC_SMALL, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Y velocity should be 0., not %g", (double)PetscRealPart(vres[p * dim + 1]));
17118214e71cSJoe     }
17128214e71cSJoe     if (pr) PetscCall(PetscSynchronizedFlush(PETSC_COMM_WORLD, PETSC_STDOUT));
17138214e71cSJoe   }
17148214e71cSJoe   PetscCall(VecRestoreArray(Vres, &vres));
17158214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
17168214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initVelocity", NULL, NULL, (void **)&vel));
17178214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "E_field", NULL, NULL, (void **)&E));
17188214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
17198214e71cSJoe }
17208214e71cSJoe 
17218214e71cSJoe static PetscErrorCode CreateSolution(TS ts)
17228214e71cSJoe {
17238214e71cSJoe   DM       sw;
17248214e71cSJoe   Vec      u;
17258214e71cSJoe   PetscInt dim, Np;
17268214e71cSJoe 
17278214e71cSJoe   PetscFunctionBegin;
17288214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
17298214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
17308214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
17318214e71cSJoe   PetscCall(VecCreate(PETSC_COMM_WORLD, &u));
17328214e71cSJoe   PetscCall(VecSetBlockSize(u, dim));
17338214e71cSJoe   PetscCall(VecSetSizes(u, 2 * Np * dim, PETSC_DECIDE));
17348214e71cSJoe   PetscCall(VecSetUp(u));
17358214e71cSJoe   PetscCall(TSSetSolution(ts, u));
17368214e71cSJoe   PetscCall(VecDestroy(&u));
17378214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
17388214e71cSJoe }
17398214e71cSJoe 
17408214e71cSJoe static PetscErrorCode SetProblem(TS ts)
17418214e71cSJoe {
17428214e71cSJoe   AppCtx *user;
17438214e71cSJoe   DM      sw;
17448214e71cSJoe 
17458214e71cSJoe   PetscFunctionBegin;
17468214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
17478214e71cSJoe   PetscCall(DMGetApplicationContext(sw, (void **)&user));
17488214e71cSJoe   // Define unified system for (X, V)
17498214e71cSJoe   {
17508214e71cSJoe     Mat      J;
17518214e71cSJoe     PetscInt dim, Np;
17528214e71cSJoe 
17538214e71cSJoe     PetscCall(DMGetDimension(sw, &dim));
17548214e71cSJoe     PetscCall(DMSwarmGetLocalSize(sw, &Np));
17558214e71cSJoe     PetscCall(MatCreate(PETSC_COMM_WORLD, &J));
17568214e71cSJoe     PetscCall(MatSetSizes(J, 2 * Np * dim, 2 * Np * dim, PETSC_DECIDE, PETSC_DECIDE));
17578214e71cSJoe     PetscCall(MatSetBlockSize(J, 2 * dim));
17588214e71cSJoe     PetscCall(MatSetFromOptions(J));
17598214e71cSJoe     PetscCall(MatSetUp(J));
17608214e71cSJoe     PetscCall(TSSetRHSFunction(ts, NULL, RHSFunction, user));
17618214e71cSJoe     PetscCall(TSSetRHSJacobian(ts, J, J, RHSJacobian, user));
17628214e71cSJoe     PetscCall(MatDestroy(&J));
17638214e71cSJoe   }
17648214e71cSJoe   /* Define split system for X and V */
17658214e71cSJoe   {
17668214e71cSJoe     Vec             u;
17678214e71cSJoe     IS              isx, isv, istmp;
17688214e71cSJoe     const PetscInt *idx;
17698214e71cSJoe     PetscInt        dim, Np, rstart;
17708214e71cSJoe 
17718214e71cSJoe     PetscCall(TSGetSolution(ts, &u));
17728214e71cSJoe     PetscCall(DMGetDimension(sw, &dim));
17738214e71cSJoe     PetscCall(DMSwarmGetLocalSize(sw, &Np));
17748214e71cSJoe     PetscCall(VecGetOwnershipRange(u, &rstart, NULL));
17758214e71cSJoe     PetscCall(ISCreateStride(PETSC_COMM_WORLD, Np, (rstart / dim) + 0, 2, &istmp));
17768214e71cSJoe     PetscCall(ISGetIndices(istmp, &idx));
17778214e71cSJoe     PetscCall(ISCreateBlock(PETSC_COMM_WORLD, dim, Np, idx, PETSC_COPY_VALUES, &isx));
17788214e71cSJoe     PetscCall(ISRestoreIndices(istmp, &idx));
17798214e71cSJoe     PetscCall(ISDestroy(&istmp));
17808214e71cSJoe     PetscCall(ISCreateStride(PETSC_COMM_WORLD, Np, (rstart / dim) + 1, 2, &istmp));
17818214e71cSJoe     PetscCall(ISGetIndices(istmp, &idx));
17828214e71cSJoe     PetscCall(ISCreateBlock(PETSC_COMM_WORLD, dim, Np, idx, PETSC_COPY_VALUES, &isv));
17838214e71cSJoe     PetscCall(ISRestoreIndices(istmp, &idx));
17848214e71cSJoe     PetscCall(ISDestroy(&istmp));
17858214e71cSJoe     PetscCall(TSRHSSplitSetIS(ts, "position", isx));
17868214e71cSJoe     PetscCall(TSRHSSplitSetIS(ts, "momentum", isv));
17878214e71cSJoe     PetscCall(ISDestroy(&isx));
17888214e71cSJoe     PetscCall(ISDestroy(&isv));
17898214e71cSJoe     PetscCall(TSRHSSplitSetRHSFunction(ts, "position", NULL, RHSFunctionX, user));
17908214e71cSJoe     PetscCall(TSRHSSplitSetRHSFunction(ts, "momentum", NULL, RHSFunctionV, user));
17918214e71cSJoe   }
17928214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
17938214e71cSJoe }
17948214e71cSJoe 
17958214e71cSJoe static PetscErrorCode DMSwarmTSRedistribute(TS ts)
17968214e71cSJoe {
17978214e71cSJoe   DM        sw;
17988214e71cSJoe   Vec       u;
17998214e71cSJoe   PetscReal t, maxt, dt;
18008214e71cSJoe   PetscInt  n, maxn;
18018214e71cSJoe 
18028214e71cSJoe   PetscFunctionBegin;
18038214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
18048214e71cSJoe   PetscCall(TSGetTime(ts, &t));
18058214e71cSJoe   PetscCall(TSGetMaxTime(ts, &maxt));
18068214e71cSJoe   PetscCall(TSGetTimeStep(ts, &dt));
18078214e71cSJoe   PetscCall(TSGetStepNumber(ts, &n));
18088214e71cSJoe   PetscCall(TSGetMaxSteps(ts, &maxn));
18098214e71cSJoe 
18108214e71cSJoe   PetscCall(TSReset(ts));
18118214e71cSJoe   PetscCall(TSSetDM(ts, sw));
18128214e71cSJoe   PetscCall(TSSetFromOptions(ts));
18138214e71cSJoe   PetscCall(TSSetTime(ts, t));
18148214e71cSJoe   PetscCall(TSSetMaxTime(ts, maxt));
18158214e71cSJoe   PetscCall(TSSetTimeStep(ts, dt));
18168214e71cSJoe   PetscCall(TSSetStepNumber(ts, n));
18178214e71cSJoe   PetscCall(TSSetMaxSteps(ts, maxn));
18188214e71cSJoe 
18198214e71cSJoe   PetscCall(CreateSolution(ts));
18208214e71cSJoe   PetscCall(SetProblem(ts));
18218214e71cSJoe   PetscCall(TSGetSolution(ts, &u));
18228214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
18238214e71cSJoe }
18248214e71cSJoe 
18258214e71cSJoe PetscErrorCode line(PetscInt dim, PetscReal time, const PetscReal dummy[], PetscInt p, PetscScalar x[], void *ctx)
18268214e71cSJoe {
18278214e71cSJoe   DM        sw, cdm;
18288214e71cSJoe   PetscInt  Np;
18298214e71cSJoe   PetscReal low[2], high[2];
18308214e71cSJoe   AppCtx   *user = (AppCtx *)ctx;
18318214e71cSJoe 
18328214e71cSJoe   sw = user->swarm;
18338214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &cdm));
18348214e71cSJoe   // Get the bounding box so we can equally space the particles
18358214e71cSJoe   PetscCall(DMGetLocalBoundingBox(cdm, low, high));
18368214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
18378214e71cSJoe   // shift it by h/2 so nothing is initialized directly on a boundary
18388214e71cSJoe   x[0] = ((high[0] - low[0]) / Np) * (p + 0.5);
18398214e71cSJoe   x[1] = 0.;
18408214e71cSJoe   return PETSC_SUCCESS;
18418214e71cSJoe }
18428214e71cSJoe 
1843b80bf5b1SJoe Pusztay /*
18448214e71cSJoe   InitializeSolveAndSwarm - Set the solution values to the swarm coordinates and velocities, and also possibly set the initial values.
18458214e71cSJoe 
18468214e71cSJoe   Input Parameters:
18478214e71cSJoe + ts         - The TS
18488214e71cSJoe - useInitial - Flag to also set the initial conditions to the current coodinates and velocities and setup the problem
18498214e71cSJoe 
18508214e71cSJoe   Output Parameters:
18518214e71cSJoe . u - The initialized solution vector
18528214e71cSJoe 
18538214e71cSJoe   Level: advanced
18548214e71cSJoe 
18558214e71cSJoe .seealso: InitializeSolve()
1856b80bf5b1SJoe Pusztay */
18578214e71cSJoe static PetscErrorCode InitializeSolveAndSwarm(TS ts, PetscBool useInitial)
1858d71ae5a4SJacob Faibussowitsch {
18598214e71cSJoe   DM       sw;
18608214e71cSJoe   Vec      u, gc, gv, gc0, gv0;
18618214e71cSJoe   IS       isx, isv;
18628214e71cSJoe   PetscInt dim;
18638214e71cSJoe   AppCtx  *user;
1864b80bf5b1SJoe Pusztay 
1865b80bf5b1SJoe Pusztay   PetscFunctionBeginUser;
18668214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
18678214e71cSJoe   PetscCall(DMGetApplicationContext(sw, &user));
18688214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
18698214e71cSJoe   if (useInitial) {
18708214e71cSJoe     PetscReal v0[2] = {1., 0.};
18718214e71cSJoe     if (user->perturbed_weights) {
18728214e71cSJoe       PetscCall(InitializeParticles_PerturbedWeights(sw, user));
18738214e71cSJoe     } else {
18748214e71cSJoe       PetscCall(DMSwarmComputeLocalSizeFromOptions(sw));
18758214e71cSJoe       PetscCall(DMSwarmInitializeCoordinates(sw));
18768214e71cSJoe       if (user->fake_1D) {
18778214e71cSJoe         PetscCall(InitializeVelocities_Fake1D(sw, user));
18788214e71cSJoe       } else {
18798214e71cSJoe         PetscCall(DMSwarmInitializeVelocitiesFromOptions(sw, v0));
18808214e71cSJoe       }
18818214e71cSJoe     }
18828214e71cSJoe     PetscCall(DMSwarmMigrate(sw, PETSC_TRUE));
18838214e71cSJoe     PetscCall(DMSwarmTSRedistribute(ts));
18848214e71cSJoe   }
18858214e71cSJoe   PetscCall(TSGetSolution(ts, &u));
18868214e71cSJoe   PetscCall(TSRHSSplitGetIS(ts, "position", &isx));
18878214e71cSJoe   PetscCall(TSRHSSplitGetIS(ts, "momentum", &isv));
18888214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, DMSwarmPICField_coor, &gc));
18898214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "initCoordinates", &gc0));
18908214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "velocity", &gv));
18918214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "initVelocity", &gv0));
18928214e71cSJoe   if (useInitial) {
18938214e71cSJoe     PetscCall(VecCopy(gc, gc0));
18948214e71cSJoe     PetscCall(VecCopy(gv, gv0));
18958214e71cSJoe   }
18968214e71cSJoe   PetscCall(VecISCopy(u, isx, SCATTER_FORWARD, gc));
18978214e71cSJoe   PetscCall(VecISCopy(u, isv, SCATTER_FORWARD, gv));
18988214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, DMSwarmPICField_coor, &gc));
18998214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "initCoordinates", &gc0));
19008214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "velocity", &gv));
19018214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "initVelocity", &gv0));
19028214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
19038214e71cSJoe }
19048214e71cSJoe 
19058214e71cSJoe static PetscErrorCode InitializeSolve(TS ts, Vec u)
1906b80bf5b1SJoe Pusztay {
19078214e71cSJoe   PetscFunctionBegin;
19088214e71cSJoe   PetscCall(TSSetSolution(ts, u));
19098214e71cSJoe   PetscCall(InitializeSolveAndSwarm(ts, PETSC_TRUE));
19108214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
1911b80bf5b1SJoe Pusztay }
1912b80bf5b1SJoe Pusztay 
19138214e71cSJoe static PetscErrorCode ComputeError(TS ts, Vec U, Vec E)
19148214e71cSJoe {
19158214e71cSJoe   MPI_Comm           comm;
19168214e71cSJoe   DM                 sw;
19178214e71cSJoe   AppCtx            *user;
19188214e71cSJoe   const PetscScalar *u;
19198214e71cSJoe   const PetscReal   *coords, *vel;
19208214e71cSJoe   PetscScalar       *e;
19218214e71cSJoe   PetscReal          t;
19228214e71cSJoe   PetscInt           dim, Np, p;
1923b80bf5b1SJoe Pusztay 
19248214e71cSJoe   PetscFunctionBeginUser;
19258214e71cSJoe   PetscCall(PetscObjectGetComm((PetscObject)ts, &comm));
19268214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
19278214e71cSJoe   PetscCall(DMGetApplicationContext(sw, &user));
19288214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
19298214e71cSJoe   PetscCall(TSGetSolveTime(ts, &t));
19308214e71cSJoe   PetscCall(VecGetArray(E, &e));
19318214e71cSJoe   PetscCall(VecGetArrayRead(U, &u));
19328214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
19338214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
19348214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initVelocity", NULL, NULL, (void **)&vel));
19358214e71cSJoe   Np /= 2 * dim;
19368214e71cSJoe   for (p = 0; p < Np; ++p) {
19378214e71cSJoe     /* TODO generalize initial conditions and project into plane instead of assuming x-y */
19388214e71cSJoe     const PetscReal    r0    = DMPlex_NormD_Internal(dim, &coords[p * dim]);
19398214e71cSJoe     const PetscReal    th0   = PetscAtan2Real(coords[p * dim + 1], coords[p * dim + 0]);
19408214e71cSJoe     const PetscReal    v0    = DMPlex_NormD_Internal(dim, &vel[p * dim]);
19418214e71cSJoe     const PetscReal    omega = v0 / r0;
19428214e71cSJoe     const PetscReal    ct    = PetscCosReal(omega * t + th0);
19438214e71cSJoe     const PetscReal    st    = PetscSinReal(omega * t + th0);
19448214e71cSJoe     const PetscScalar *x     = &u[(p * 2 + 0) * dim];
19458214e71cSJoe     const PetscScalar *v     = &u[(p * 2 + 1) * dim];
19468214e71cSJoe     const PetscReal    xe[3] = {r0 * ct, r0 * st, 0.0};
19478214e71cSJoe     const PetscReal    ve[3] = {-v0 * st, v0 * ct, 0.0};
19488214e71cSJoe     PetscInt           d;
19498214e71cSJoe 
19508214e71cSJoe     for (d = 0; d < dim; ++d) {
19518214e71cSJoe       e[(p * 2 + 0) * dim + d] = x[d] - xe[d];
19528214e71cSJoe       e[(p * 2 + 1) * dim + d] = v[d] - ve[d];
1953b80bf5b1SJoe Pusztay     }
19548214e71cSJoe     if (user->error) {
19558214e71cSJoe       const PetscReal en   = 0.5 * DMPlex_DotRealD_Internal(dim, v, v);
19568214e71cSJoe       const PetscReal exen = 0.5 * PetscSqr(v0);
19578214e71cSJoe       PetscCall(PetscPrintf(comm, "t %.4g: p%" PetscInt_FMT " error [%.2g %.2g] sol [(%.6lf %.6lf) (%.6lf %.6lf)] exact [(%.6lf %.6lf) (%.6lf %.6lf)] energy/exact energy %g / %g (%.10lf%%)\n", (double)t, p, (double)DMPlex_NormD_Internal(dim, &e[(p * 2 + 0) * dim]), (double)DMPlex_NormD_Internal(dim, &e[(p * 2 + 1) * dim]), (double)x[0], (double)x[1], (double)v[0], (double)v[1], (double)xe[0], (double)xe[1], (double)ve[0], (double)ve[1], (double)en, (double)exen, (double)(PetscAbsReal(exen - en) * 100. / exen)));
1958b80bf5b1SJoe Pusztay     }
19598214e71cSJoe   }
19608214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
19618214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initVelocity", NULL, NULL, (void **)&vel));
19628214e71cSJoe   PetscCall(VecRestoreArrayRead(U, &u));
19638214e71cSJoe   PetscCall(VecRestoreArray(E, &e));
19648214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
19658214e71cSJoe }
19668214e71cSJoe 
19678214e71cSJoe static PetscErrorCode MigrateParticles(TS ts)
19688214e71cSJoe {
19698214e71cSJoe   DM               sw, cdm;
19708214e71cSJoe   const PetscReal *L;
19718214e71cSJoe 
19728214e71cSJoe   PetscFunctionBeginUser;
19738214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
19748214e71cSJoe   PetscCall(DMViewFromOptions(sw, NULL, "-migrate_view_pre"));
19758214e71cSJoe   {
19768214e71cSJoe     Vec        u, gc, gv, position, momentum;
19778214e71cSJoe     IS         isx, isv;
19788214e71cSJoe     PetscReal *pos, *mom;
19798214e71cSJoe 
19808214e71cSJoe     PetscCall(TSGetSolution(ts, &u));
19818214e71cSJoe     PetscCall(TSRHSSplitGetIS(ts, "position", &isx));
19828214e71cSJoe     PetscCall(TSRHSSplitGetIS(ts, "momentum", &isv));
19838214e71cSJoe     PetscCall(VecGetSubVector(u, isx, &position));
19848214e71cSJoe     PetscCall(VecGetSubVector(u, isv, &momentum));
19858214e71cSJoe     PetscCall(VecGetArray(position, &pos));
19868214e71cSJoe     PetscCall(VecGetArray(momentum, &mom));
19878214e71cSJoe     PetscCall(DMSwarmCreateGlobalVectorFromField(sw, DMSwarmPICField_coor, &gc));
19888214e71cSJoe     PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "velocity", &gv));
19898214e71cSJoe     PetscCall(VecISCopy(u, isx, SCATTER_REVERSE, gc));
19908214e71cSJoe     PetscCall(VecISCopy(u, isv, SCATTER_REVERSE, gv));
19918214e71cSJoe 
19928214e71cSJoe     PetscCall(DMSwarmGetCellDM(sw, &cdm));
19938214e71cSJoe     PetscCall(DMGetPeriodicity(cdm, NULL, NULL, &L));
19948214e71cSJoe     if ((L[0] || L[1]) >= 0.) {
19958214e71cSJoe       PetscReal *x, *v, upper[3], lower[3];
19968214e71cSJoe       PetscInt   Np, dim;
19978214e71cSJoe 
19988214e71cSJoe       PetscCall(DMSwarmGetLocalSize(sw, &Np));
19998214e71cSJoe       PetscCall(DMGetDimension(cdm, &dim));
20008214e71cSJoe       PetscCall(DMGetBoundingBox(cdm, lower, upper));
20018214e71cSJoe       PetscCall(VecGetArray(gc, &x));
20028214e71cSJoe       PetscCall(VecGetArray(gv, &v));
20038214e71cSJoe       for (PetscInt p = 0; p < Np; ++p) {
20048214e71cSJoe         for (PetscInt d = 0; d < dim; ++d) {
20058214e71cSJoe           if (pos[p * dim + d] < lower[d]) {
20068214e71cSJoe             x[p * dim + d] = pos[p * dim + d] + (upper[d] - lower[d]);
20078214e71cSJoe           } else if (pos[p * dim + d] > upper[d]) {
20088214e71cSJoe             x[p * dim + d] = pos[p * dim + d] - (upper[d] - lower[d]);
20098214e71cSJoe           } else {
20108214e71cSJoe             x[p * dim + d] = pos[p * dim + d];
20118214e71cSJoe           }
20128214e71cSJoe           PetscCheck(x[p * dim + d] >= lower[d] && x[p * dim + d] <= upper[d], PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "p: %" PetscInt_FMT "x[%" PetscInt_FMT "] %g", p, d, (double)x[p * dim + d]);
20138214e71cSJoe           v[p * dim + d] = mom[p * dim + d];
20148214e71cSJoe         }
20158214e71cSJoe       }
20168214e71cSJoe       PetscCall(VecRestoreArray(gc, &x));
20178214e71cSJoe       PetscCall(VecRestoreArray(gv, &v));
20188214e71cSJoe     }
20198214e71cSJoe     PetscCall(VecRestoreArray(position, &pos));
20208214e71cSJoe     PetscCall(VecRestoreArray(momentum, &mom));
20218214e71cSJoe     PetscCall(VecRestoreSubVector(u, isx, &position));
20228214e71cSJoe     PetscCall(VecRestoreSubVector(u, isv, &momentum));
20238214e71cSJoe     PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "velocity", &gv));
20248214e71cSJoe     PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, DMSwarmPICField_coor, &gc));
20258214e71cSJoe   }
20268214e71cSJoe   PetscCall(DMSwarmMigrate(sw, PETSC_TRUE));
20278214e71cSJoe   PetscCall(DMSwarmTSRedistribute(ts));
20288214e71cSJoe   PetscCall(InitializeSolveAndSwarm(ts, PETSC_FALSE));
20293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2030b80bf5b1SJoe Pusztay }
2031b80bf5b1SJoe Pusztay 
2032d71ae5a4SJacob Faibussowitsch int main(int argc, char **argv)
2033d71ae5a4SJacob Faibussowitsch {
2034b80bf5b1SJoe Pusztay   DM        dm, sw;
20358214e71cSJoe   TS        ts;
20368214e71cSJoe   Vec       u;
20378214e71cSJoe   PetscReal dt;
20388214e71cSJoe   PetscInt  maxn;
2039b80bf5b1SJoe Pusztay   AppCtx    user;
2040b80bf5b1SJoe Pusztay 
20419566063dSJacob Faibussowitsch   PetscCall(PetscInitialize(&argc, &argv, NULL, help));
20428214e71cSJoe   PetscCall(ProcessOptions(PETSC_COMM_WORLD, &user));
20438214e71cSJoe   PetscCall(PetscBagCreate(PETSC_COMM_SELF, sizeof(Parameter), &user.bag));
20448214e71cSJoe   PetscCall(CreateMesh(PETSC_COMM_WORLD, &user, &dm));
20458214e71cSJoe   PetscCall(CreatePoisson(dm, &user));
20468214e71cSJoe   PetscCall(CreateSwarm(dm, &user, &sw));
20478214e71cSJoe   PetscCall(SetupParameters(PETSC_COMM_WORLD, &user));
20488214e71cSJoe   PetscCall(InitializeConstants(sw, &user));
20498214e71cSJoe   PetscCall(DMSetApplicationContext(sw, &user));
2050b80bf5b1SJoe Pusztay 
20518214e71cSJoe   PetscCall(TSCreate(PETSC_COMM_WORLD, &ts));
20528214e71cSJoe   PetscCall(TSSetProblemType(ts, TS_NONLINEAR));
20539566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts, sw));
20548214e71cSJoe   PetscCall(TSSetMaxTime(ts, 0.1));
20558214e71cSJoe   PetscCall(TSSetTimeStep(ts, 0.00001));
20568214e71cSJoe   PetscCall(TSSetMaxSteps(ts, 100));
20578214e71cSJoe   PetscCall(TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP));
20588214e71cSJoe 
20598214e71cSJoe   if (user.efield_monitor) PetscCall(TSMonitorSet(ts, MonitorEField, &user, NULL));
20608214e71cSJoe   if (user.initial_monitor) PetscCall(TSMonitorSet(ts, MonitorInitialConditions, &user, NULL));
20618214e71cSJoe   if (user.monitor_positions) PetscCall(TSMonitorSet(ts, MonitorPositions_2D, &user, NULL));
20628214e71cSJoe   if (user.poisson_monitor) PetscCall(TSMonitorSet(ts, MonitorPoisson, &user, NULL));
20638214e71cSJoe 
20648214e71cSJoe   PetscCall(TSSetFromOptions(ts));
20658214e71cSJoe   PetscCall(TSGetTimeStep(ts, &dt));
20668214e71cSJoe   PetscCall(TSGetMaxSteps(ts, &maxn));
20678214e71cSJoe   user.steps    = maxn;
20688214e71cSJoe   user.stepSize = dt;
20698214e71cSJoe   PetscCall(SetupContext(dm, sw, &user));
20708214e71cSJoe   PetscCall(DMSwarmVectorDefineField(sw, "velocity"));
20718214e71cSJoe   PetscCall(TSSetComputeInitialCondition(ts, InitializeSolve));
20728214e71cSJoe   PetscCall(TSSetComputeExactError(ts, ComputeError));
20738214e71cSJoe   PetscCall(TSSetPostStep(ts, MigrateParticles));
20748214e71cSJoe   PetscCall(CreateSolution(ts));
20758214e71cSJoe   PetscCall(TSGetSolution(ts, &u));
20768214e71cSJoe   PetscCall(TSComputeInitialCondition(ts, u));
20778214e71cSJoe   PetscCall(CheckNonNegativeWeights(sw, &user));
20788214e71cSJoe   PetscCall(TSSolve(ts, NULL));
20798214e71cSJoe 
20809566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&user.snes));
20819566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&ts));
20829566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&sw));
20839566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&dm));
20848214e71cSJoe   PetscCall(DestroyContext(&user));
20859566063dSJacob Faibussowitsch   PetscCall(PetscFinalize());
2086b122ec5aSJacob Faibussowitsch   return 0;
2087b80bf5b1SJoe Pusztay }
2088b80bf5b1SJoe Pusztay 
2089b80bf5b1SJoe Pusztay /*TEST
2090b80bf5b1SJoe Pusztay 
2091b80bf5b1SJoe Pusztay    build:
20928214e71cSJoe     requires: !complex double
20938214e71cSJoe 
20948214e71cSJoe   # This tests that we can put particles in a box and compute the Coulomb force
20958214e71cSJoe   # Recommend -draw_size 500,500
20968214e71cSJoe    testset:
20978214e71cSJoe      requires: defined(PETSC_HAVE_EXECUTABLE_EXPORT)
20988214e71cSJoe      args: -dm_plex_dim 2 -fake_1D -dm_plex_simplex 0 -dm_plex_box_faces 20,1 \
20998214e71cSJoe              -dm_plex_box_lower 0,-1 -dm_plex_box_upper 12.5664,1 \
2100b80bf5b1SJoe Pusztay              -dm_plex_box_bd periodic,none \
21018214e71cSJoe            -dm_swarm_coordinate_density constant -dm_swarm_num_particles 100 \
21028214e71cSJoe            -sigma 1.0e-8 -timeScale 2.0e-14 \
21038214e71cSJoe            -ts_type basicsymplectic -ts_basicsymplectic_type 1 \
21048214e71cSJoe              -ts_monitor_sp_swarm -ts_monitor_sp_swarm_retain 0 -ts_monitor_sp_swarm_phase 0 \
21058214e71cSJoe            -output_step 50 -check_vel_res
21068214e71cSJoe      test:
21078214e71cSJoe        suffix: none_1d
21088214e71cSJoe        args: -em_type none -error
21098214e71cSJoe      test:
21108214e71cSJoe        suffix: coulomb_1d
21118214e71cSJoe        args: -em_type coulomb
21128214e71cSJoe 
21138214e71cSJoe    # for viewers
21148214e71cSJoe    #-ts_monitor_sp_swarm_phase -ts_monitor_sp_swarm -em_snes_monitor -ts_monitor_sp_swarm_multi_species 0 -ts_monitor_sp_swarm_retain 0
21158214e71cSJoe    testset:
21168214e71cSJoe      nsize: {{1 2}}
21178214e71cSJoe      requires: defined(PETSC_HAVE_EXECUTABLE_EXPORT)
21188214e71cSJoe      args: -dm_plex_dim 2 -fake_1D -dm_plex_simplex 0 -dm_plex_box_faces 36,1 \
21198214e71cSJoe              -dm_plex_box_lower 0.,-0.5 -dm_plex_box_upper 12.5664,0.5 \
21208214e71cSJoe              -dm_plex_box_bd periodic,none \
21218214e71cSJoe            -vdm_plex_dim 1 -vdm_plex_simplex 0 -vdm_plex_box_faces 10 \
21228214e71cSJoe              -vdm_plex_box_lower -3 -vdm_plex_box_upper 3 \
21238214e71cSJoe            -dm_swarm_num_species 1 -dm_swarm_num_particles 360 \
21248214e71cSJoe            -twostream -charges -1.,1. -sigma 1.0e-8 \
21258214e71cSJoe              -cosine_coefficients 0.01,0.5 -perturbed_weights -total_weight 1. \
21268214e71cSJoe            -ts_type basicsymplectic -ts_basicsymplectic_type 2 \
21278214e71cSJoe              -ts_dt 0.01 -ts_max_time 5 -ts_max_steps 10 \
21288214e71cSJoe            -em_snes_atol 1.e-15 -em_snes_error_if_not_converged -em_ksp_error_if_not_converged \
21298214e71cSJoe            -output_step 1 -check_vel_res
21308214e71cSJoe      test:
21318214e71cSJoe        suffix: two_stream_c0
21328214e71cSJoe        args: -em_type primal -petscfe_default_quadrature_order 2 -petscspace_degree 2 -em_pc_type svd
21338214e71cSJoe      test:
21348214e71cSJoe        suffix: two_stream_rt
21358214e71cSJoe        requires: superlu_dist
21368214e71cSJoe        args: -em_type mixed \
21378214e71cSJoe                -potential_petscspace_degree 0 \
21388214e71cSJoe                -potential_petscdualspace_lagrange_use_moments \
21398214e71cSJoe                -potential_petscdualspace_lagrange_moment_order 2 \
21408214e71cSJoe                -field_petscspace_degree 2 -field_petscfe_default_quadrature_order 1 \
21418214e71cSJoe                -field_petscspace_type sum \
21428214e71cSJoe                  -field_petscspace_variables 2 \
21438214e71cSJoe                  -field_petscspace_components 2 \
21448214e71cSJoe                  -field_petscspace_sum_spaces 2 \
21458214e71cSJoe                  -field_petscspace_sum_concatenate true \
21468214e71cSJoe                  -field_sumcomp_0_petscspace_variables 2 \
21478214e71cSJoe                  -field_sumcomp_0_petscspace_type tensor \
21488214e71cSJoe                  -field_sumcomp_0_petscspace_tensor_spaces 2 \
21498214e71cSJoe                  -field_sumcomp_0_petscspace_tensor_uniform false \
21508214e71cSJoe                  -field_sumcomp_0_tensorcomp_0_petscspace_degree 1 \
21518214e71cSJoe                  -field_sumcomp_0_tensorcomp_1_petscspace_degree 0 \
21528214e71cSJoe                  -field_sumcomp_1_petscspace_variables 2 \
21538214e71cSJoe                  -field_sumcomp_1_petscspace_type tensor \
21548214e71cSJoe                  -field_sumcomp_1_petscspace_tensor_spaces 2 \
21558214e71cSJoe                  -field_sumcomp_1_petscspace_tensor_uniform false \
21568214e71cSJoe                  -field_sumcomp_1_tensorcomp_0_petscspace_degree 0 \
21578214e71cSJoe                  -field_sumcomp_1_tensorcomp_1_petscspace_degree 1 \
21588214e71cSJoe                -field_petscdualspace_form_degree -1 \
21598214e71cSJoe                -field_petscdualspace_order 1 \
21608214e71cSJoe                -field_petscdualspace_lagrange_trimmed true \
21618214e71cSJoe              -em_snes_error_if_not_converged \
21628214e71cSJoe              -em_ksp_type preonly -em_ksp_error_if_not_converged \
21638214e71cSJoe              -em_pc_type fieldsplit -em_pc_fieldsplit_type schur \
21648214e71cSJoe                -em_pc_fieldsplit_schur_fact_type full -em_pc_fieldsplit_schur_precondition full \
21658214e71cSJoe                -em_fieldsplit_field_pc_type lu \
21668214e71cSJoe                  -em_fieldsplit_field_pc_factor_mat_solver_type superlu_dist \
21678214e71cSJoe                -em_fieldsplit_potential_pc_type svd
21688214e71cSJoe 
21698214e71cSJoe    # For verification, we use
21708214e71cSJoe    # -dm_plex_box_faces 100,1 -vdm_plex_box_faces 8000 -dm_swarm_num_particles 800000
21718214e71cSJoe    # -ts_monitor_sp_swarm_multi_species 0 -ts_monitor_sp_swarm_retain 0 -ts_monitor_sp_swarm_phase 1 -draw_size 500,500
21728214e71cSJoe    testset:
21738214e71cSJoe      nsize: {{1 2}}
21748214e71cSJoe      requires: defined(PETSC_HAVE_EXECUTABLE_EXPORT)
21758214e71cSJoe      args: -dm_plex_dim 2 -fake_1D -dm_plex_simplex 0 -dm_plex_box_faces 10,1 \
21768214e71cSJoe              -dm_plex_box_lower 0.,-0.5 -dm_plex_box_upper 12.5664,0.5 \
21778214e71cSJoe              -dm_plex_box_bd periodic,none \
21788214e71cSJoe            -vdm_plex_dim 1 -vdm_plex_simplex 0 -vdm_plex_box_faces 10 \
21798214e71cSJoe              -vdm_plex_box_lower -10 -vdm_plex_box_upper 10 \
21808214e71cSJoe            -dm_swarm_num_species 1 -dm_swarm_num_particles 100 \
21818214e71cSJoe            -charges -1.,1. \
21828214e71cSJoe              -cosine_coefficients 0.01,0.5 -perturbed_weights -total_weight 1. \
21838214e71cSJoe            -ts_type basicsymplectic -ts_basicsymplectic_type 1 \
21848214e71cSJoe              -ts_dt 0.03 -ts_max_time 500 -ts_max_steps 1 \
21858214e71cSJoe            -em_snes_atol 1.e-12 -em_snes_error_if_not_converged -em_ksp_error_if_not_converged \
21868214e71cSJoe            -output_step 1 -check_vel_res
21878214e71cSJoe 
21888214e71cSJoe      test:
21898214e71cSJoe        suffix: uniform_equilibrium_1d
21908214e71cSJoe        args: -cosine_coefficients 0.0,0.5 -em_type primal -petscspace_degree 1 -em_pc_type svd
21918214e71cSJoe      test:
21928214e71cSJoe        suffix: uniform_primal_1d
21938214e71cSJoe        args: -em_type primal -petscspace_degree 1 -em_pc_type svd
21948214e71cSJoe      test:
21958214e71cSJoe        requires: superlu_dist
21968214e71cSJoe        suffix: uniform_mixed_1d
21978214e71cSJoe        args: -em_type mixed \
21988214e71cSJoe                -potential_petscspace_degree 0 \
21998214e71cSJoe                -potential_petscdualspace_lagrange_use_moments \
22008214e71cSJoe                -potential_petscdualspace_lagrange_moment_order 2 \
22018214e71cSJoe                -field_petscspace_degree 2 -field_petscfe_default_quadrature_order 1 \
22028214e71cSJoe                -field_petscspace_type sum \
22038214e71cSJoe                  -field_petscspace_variables 2 \
22048214e71cSJoe                  -field_petscspace_components 2 \
22058214e71cSJoe                  -field_petscspace_sum_spaces 2 \
22068214e71cSJoe                  -field_petscspace_sum_concatenate true \
22078214e71cSJoe                  -field_sumcomp_0_petscspace_variables 2 \
22088214e71cSJoe                  -field_sumcomp_0_petscspace_type tensor \
22098214e71cSJoe                  -field_sumcomp_0_petscspace_tensor_spaces 2 \
22108214e71cSJoe                  -field_sumcomp_0_petscspace_tensor_uniform false \
22118214e71cSJoe                  -field_sumcomp_0_tensorcomp_0_petscspace_degree 1 \
22128214e71cSJoe                  -field_sumcomp_0_tensorcomp_1_petscspace_degree 0 \
22138214e71cSJoe                  -field_sumcomp_1_petscspace_variables 2 \
22148214e71cSJoe                  -field_sumcomp_1_petscspace_type tensor \
22158214e71cSJoe                  -field_sumcomp_1_petscspace_tensor_spaces 2 \
22168214e71cSJoe                  -field_sumcomp_1_petscspace_tensor_uniform false \
22178214e71cSJoe                  -field_sumcomp_1_tensorcomp_0_petscspace_degree 0 \
22188214e71cSJoe                  -field_sumcomp_1_tensorcomp_1_petscspace_degree 1 \
22198214e71cSJoe                -field_petscdualspace_form_degree -1 \
22208214e71cSJoe                -field_petscdualspace_order 1 \
22218214e71cSJoe                -field_petscdualspace_lagrange_trimmed true \
22228214e71cSJoe              -em_snes_error_if_not_converged \
22238214e71cSJoe              -em_ksp_type preonly -em_ksp_error_if_not_converged \
22248214e71cSJoe              -em_pc_type fieldsplit -em_pc_fieldsplit_type schur \
22258214e71cSJoe                -em_pc_fieldsplit_schur_fact_type full -em_pc_fieldsplit_schur_precondition full \
22268214e71cSJoe                -em_fieldsplit_field_pc_type lu \
22278214e71cSJoe                  -em_fieldsplit_field_pc_factor_mat_solver_type superlu_dist \
22288214e71cSJoe                -em_fieldsplit_potential_pc_type svd
22298214e71cSJoe 
2230b80bf5b1SJoe Pusztay TEST*/
2231