xref: /petsc/src/ts/tutorials/hamiltonian/ex2.c (revision 84467f862f2de26368b63ea79dccd665bcda30cd)
1*84467f86SMatthew G. Knepley #include "petscsys.h"
28214e71cSJoe static char help[] = "Landau Damping/Two Stream instability test using Vlasov-Poisson equations\n";
3b80bf5b1SJoe Pusztay 
48214e71cSJoe /*
58214e71cSJoe   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"
68214e71cSJoe   According to Lukas, good damping results come at ~16k particles per cell
78214e71cSJoe 
88214e71cSJoe   To visualize the efield use
98214e71cSJoe 
108214e71cSJoe     -monitor_efield
118214e71cSJoe 
128214e71cSJoe   To visualize the swarm distribution use
138214e71cSJoe 
148214e71cSJoe     -ts_monitor_hg_swarm
158214e71cSJoe 
168214e71cSJoe   To visualize the particles, we can use
178214e71cSJoe 
188214e71cSJoe     -ts_monitor_sp_swarm -ts_monitor_sp_swarm_retain 0 -ts_monitor_sp_swarm_phase 1 -draw_size 500,500
198214e71cSJoe 
20*84467f86SMatthew G. Knepley For a Landau Damping verification run, we use
21*84467f86SMatthew G. Knepley 
22*84467f86SMatthew G. Knepley     -dm_plex_dim 2 -fake_1D -dm_plex_simplex 0 -dm_plex_box_faces 10,1 \
23*84467f86SMatthew G. Knepley       -dm_plex_box_lower 0.,-0.5 -dm_plex_box_upper 12.5664,0.5 -dm_plex_box_bd periodic,none \
24*84467f86SMatthew G. Knepley     -vdm_plex_dim 1 -vdm_plex_simplex 0 -vdm_plex_box_faces 2000 -vdm_plex_box_lower -10 -vdm_plex_box_upper 10 \
25*84467f86SMatthew G. Knepley     -dm_swarm_num_species 1 -charges -1.,1. \
26*84467f86SMatthew G. Knepley     -cosine_coefficients 0.01,0.5 -perturbed_weights -total_weight 1. \
27*84467f86SMatthew G. Knepley     -ts_type basicsymplectic -ts_basicsymplectic_type 1 -ts_dt 0.03 -ts_max_time 500 -ts_max_steps 500 \
28*84467f86SMatthew G. Knepley     -em_type primal -petscspace_degree 1 -em_snes_atol 1.e-12 -em_snes_error_if_not_converged -em_ksp_error_if_not_converged -em_pc_type svd \
29*84467f86SMatthew G. Knepley     -output_step 100 -check_vel_res -monitor_efield -ts_monitor -log_view
30*84467f86SMatthew G. Knepley 
318214e71cSJoe */
32b80bf5b1SJoe Pusztay #include <petscts.h>
338214e71cSJoe #include <petscdmplex.h>
348214e71cSJoe #include <petscdmswarm.h>
358214e71cSJoe #include <petscfe.h>
368214e71cSJoe #include <petscds.h>
378214e71cSJoe #include <petscbag.h>
388214e71cSJoe #include <petscdraw.h>
398214e71cSJoe #include <petsc/private/dmpleximpl.h>  /* For norm and dot */
408214e71cSJoe #include <petsc/private/petscfeimpl.h> /* For interpolation */
41*84467f86SMatthew G. Knepley #include <petsc/private/dmswarmimpl.h> /* For swarm debugging */
428214e71cSJoe #include "petscdm.h"
438214e71cSJoe #include "petscdmlabel.h"
448214e71cSJoe 
458214e71cSJoe PETSC_EXTERN PetscErrorCode stream(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
468214e71cSJoe PETSC_EXTERN PetscErrorCode line(PetscInt, PetscReal, const PetscReal[], PetscInt, PetscScalar[], void *);
478214e71cSJoe 
488214e71cSJoe const char *EMTypes[] = {"primal", "mixed", "coulomb", "none", "EMType", "EM_", NULL};
498214e71cSJoe typedef enum {
508214e71cSJoe   EM_PRIMAL,
518214e71cSJoe   EM_MIXED,
528214e71cSJoe   EM_COULOMB,
538214e71cSJoe   EM_NONE
548214e71cSJoe } EMType;
558214e71cSJoe 
568214e71cSJoe typedef enum {
578214e71cSJoe   V0,
588214e71cSJoe   X0,
598214e71cSJoe   T0,
608214e71cSJoe   M0,
618214e71cSJoe   Q0,
628214e71cSJoe   PHI0,
638214e71cSJoe   POISSON,
648214e71cSJoe   VLASOV,
658214e71cSJoe   SIGMA,
668214e71cSJoe   NUM_CONSTANTS
678214e71cSJoe } ConstantType;
688214e71cSJoe typedef struct {
698214e71cSJoe   PetscScalar v0; /* Velocity scale, often the thermal velocity */
708214e71cSJoe   PetscScalar t0; /* Time scale */
718214e71cSJoe   PetscScalar x0; /* Space scale */
728214e71cSJoe   PetscScalar m0; /* Mass scale */
738214e71cSJoe   PetscScalar q0; /* Charge scale */
748214e71cSJoe   PetscScalar kb;
758214e71cSJoe   PetscScalar epsi0;
768214e71cSJoe   PetscScalar phi0;          /* Potential scale */
778214e71cSJoe   PetscScalar poissonNumber; /* Non-Dimensional Poisson Number */
788214e71cSJoe   PetscScalar vlasovNumber;  /* Non-Dimensional Vlasov Number */
798214e71cSJoe   PetscReal   sigma;         /* Nondimensional charge per length in x */
808214e71cSJoe } Parameter;
81b80bf5b1SJoe Pusztay 
82b80bf5b1SJoe Pusztay typedef struct {
838214e71cSJoe   PetscBag    bag;            /* Problem parameters */
848214e71cSJoe   PetscBool   error;          /* Flag for printing the error */
858214e71cSJoe   PetscBool   efield_monitor; /* Flag to show electric field monitor */
868214e71cSJoe   PetscBool   initial_monitor;
878214e71cSJoe   PetscBool   fake_1D;           /* Run simulation in 2D but zeroing second dimension */
888214e71cSJoe   PetscBool   perturbed_weights; /* Uniformly sample x,v space with gaussian weights */
898214e71cSJoe   PetscBool   poisson_monitor;
908214e71cSJoe   PetscInt    ostep; /* print the energy at each ostep time steps */
918214e71cSJoe   PetscInt    numParticles;
928214e71cSJoe   PetscReal   timeScale;              /* Nondimensionalizing time scale */
938214e71cSJoe   PetscReal   charges[2];             /* The charges of each species */
948214e71cSJoe   PetscReal   masses[2];              /* The masses of each species */
958214e71cSJoe   PetscReal   thermal_energy[2];      /* Thermal Energy (used to get other constants)*/
968214e71cSJoe   PetscReal   cosine_coefficients[2]; /*(alpha, k)*/
978214e71cSJoe   PetscReal   totalWeight;
988214e71cSJoe   PetscReal   stepSize;
998214e71cSJoe   PetscInt    steps;
1008214e71cSJoe   PetscReal   initVel;
1018214e71cSJoe   EMType      em; /* Type of electrostatic model */
1028214e71cSJoe   SNES        snes;
1038214e71cSJoe   PetscDraw   drawef;
1048214e71cSJoe   PetscDrawLG drawlg_ef;
1058214e71cSJoe   PetscDraw   drawic_x;
1068214e71cSJoe   PetscDraw   drawic_v;
1078214e71cSJoe   PetscDraw   drawic_w;
1088214e71cSJoe   PetscDrawHG drawhgic_x;
1098214e71cSJoe   PetscDrawHG drawhgic_v;
1108214e71cSJoe   PetscDrawHG drawhgic_w;
1118214e71cSJoe   PetscDraw   EDraw;
1128214e71cSJoe   PetscDraw   RhoDraw;
1138214e71cSJoe   PetscDraw   PotDraw;
1148214e71cSJoe   PetscDrawSP EDrawSP;
1158214e71cSJoe   PetscDrawSP RhoDrawSP;
1168214e71cSJoe   PetscDrawSP PotDrawSP;
1178214e71cSJoe   PetscBool   monitor_positions; /* Flag to show particle positins at each time step */
1188214e71cSJoe   PetscDraw   positionDraw;
1198214e71cSJoe   PetscDrawSP positionDrawSP;
1208214e71cSJoe   DM          swarm;
1218214e71cSJoe   PetscRandom random;
1228214e71cSJoe   PetscBool   twostream;
1238214e71cSJoe   PetscBool   checkweights;
1248214e71cSJoe   PetscInt    checkVRes; /* Flag to check/output velocity residuals for nightly tests */
125*84467f86SMatthew G. Knepley 
126*84467f86SMatthew G. Knepley   PetscLogEvent RhsXEvent, RhsVEvent, ESolveEvent, ETabEvent;
127b80bf5b1SJoe Pusztay } AppCtx;
128b80bf5b1SJoe Pusztay 
129d71ae5a4SJacob Faibussowitsch static PetscErrorCode ProcessOptions(MPI_Comm comm, AppCtx *options)
130d71ae5a4SJacob Faibussowitsch {
131b80bf5b1SJoe Pusztay   PetscFunctionBeginUser;
1328214e71cSJoe   PetscInt d                      = 2;
1338214e71cSJoe   PetscInt maxSpecies             = 2;
1348214e71cSJoe   options->error                  = PETSC_FALSE;
1358214e71cSJoe   options->efield_monitor         = PETSC_FALSE;
1368214e71cSJoe   options->initial_monitor        = PETSC_FALSE;
1378214e71cSJoe   options->fake_1D                = PETSC_FALSE;
1388214e71cSJoe   options->perturbed_weights      = PETSC_FALSE;
1398214e71cSJoe   options->poisson_monitor        = PETSC_FALSE;
1408214e71cSJoe   options->ostep                  = 100;
1418214e71cSJoe   options->timeScale              = 2.0e-14;
1428214e71cSJoe   options->charges[0]             = -1.0;
1438214e71cSJoe   options->charges[1]             = 1.0;
1448214e71cSJoe   options->masses[0]              = 1.0;
1458214e71cSJoe   options->masses[1]              = 1000.0;
1468214e71cSJoe   options->thermal_energy[0]      = 1.0;
1478214e71cSJoe   options->thermal_energy[1]      = 1.0;
1488214e71cSJoe   options->cosine_coefficients[0] = 0.01;
1498214e71cSJoe   options->cosine_coefficients[1] = 0.5;
1508214e71cSJoe   options->initVel                = 1;
1518214e71cSJoe   options->totalWeight            = 1.0;
1528214e71cSJoe   options->drawef                 = NULL;
1538214e71cSJoe   options->drawlg_ef              = NULL;
1548214e71cSJoe   options->drawic_x               = NULL;
1558214e71cSJoe   options->drawic_v               = NULL;
1568214e71cSJoe   options->drawic_w               = NULL;
1578214e71cSJoe   options->drawhgic_x             = NULL;
1588214e71cSJoe   options->drawhgic_v             = NULL;
1598214e71cSJoe   options->drawhgic_w             = NULL;
1608214e71cSJoe   options->EDraw                  = NULL;
1618214e71cSJoe   options->RhoDraw                = NULL;
1628214e71cSJoe   options->PotDraw                = NULL;
1638214e71cSJoe   options->EDrawSP                = NULL;
1648214e71cSJoe   options->RhoDrawSP              = NULL;
1658214e71cSJoe   options->PotDrawSP              = NULL;
1668214e71cSJoe   options->em                     = EM_COULOMB;
1678214e71cSJoe   options->numParticles           = 32768;
1688214e71cSJoe   options->monitor_positions      = PETSC_FALSE;
1698214e71cSJoe   options->positionDraw           = NULL;
1708214e71cSJoe   options->positionDrawSP         = NULL;
1718214e71cSJoe   options->twostream              = PETSC_FALSE;
1728214e71cSJoe   options->checkweights           = PETSC_FALSE;
1738214e71cSJoe   options->checkVRes              = 0;
174b80bf5b1SJoe Pusztay 
1758214e71cSJoe   PetscOptionsBegin(comm, "", "Landau Damping and Two Stream options", "DMSWARM");
1768214e71cSJoe   PetscCall(PetscOptionsBool("-error", "Flag to print the error", "ex2.c", options->error, &options->error, NULL));
1778214e71cSJoe   PetscCall(PetscOptionsBool("-monitor_efield", "Flag to show efield plot", "ex2.c", options->efield_monitor, &options->efield_monitor, NULL));
1788214e71cSJoe   PetscCall(PetscOptionsBool("-monitor_ics", "Flag to show initial condition histograms", "ex2.c", options->initial_monitor, &options->initial_monitor, NULL));
1798214e71cSJoe   PetscCall(PetscOptionsBool("-monitor_positions", "The flag to show particle positions", "ex2.c", options->monitor_positions, &options->monitor_positions, NULL));
1808214e71cSJoe   PetscCall(PetscOptionsBool("-monitor_poisson", "The flag to show charges, Efield and potential solve", "ex2.c", options->poisson_monitor, &options->poisson_monitor, NULL));
1818214e71cSJoe   PetscCall(PetscOptionsBool("-fake_1D", "Flag to run a 1D simulation (but really in 2D)", "ex2.c", options->fake_1D, &options->fake_1D, NULL));
1828214e71cSJoe   PetscCall(PetscOptionsBool("-twostream", "Run two stream instability", "ex2.c", options->twostream, &options->twostream, NULL));
1838214e71cSJoe   PetscCall(PetscOptionsBool("-perturbed_weights", "Flag to run uniform sampling with perturbed weights", "ex2.c", options->perturbed_weights, &options->perturbed_weights, NULL));
1848214e71cSJoe   PetscCall(PetscOptionsBool("-check_weights", "Ensure all particle weights are positive", "ex2.c", options->checkweights, &options->checkweights, NULL));
1858214e71cSJoe   PetscCall(PetscOptionsInt("-check_vel_res", "Check particle velocity residuals for nightly tests", "ex2.c", options->checkVRes, &options->checkVRes, NULL));
1868214e71cSJoe   PetscCall(PetscOptionsInt("-output_step", "Number of time steps between output", "ex2.c", options->ostep, &options->ostep, NULL));
1878214e71cSJoe   PetscCall(PetscOptionsReal("-timeScale", "Nondimensionalizing time scale", "ex2.c", options->timeScale, &options->timeScale, NULL));
1888214e71cSJoe   PetscCall(PetscOptionsReal("-initial_velocity", "Initial velocity of perturbed particle", "ex2.c", options->initVel, &options->initVel, NULL));
1898214e71cSJoe   PetscCall(PetscOptionsReal("-total_weight", "Total weight of all particles", "ex2.c", options->totalWeight, &options->totalWeight, NULL));
1908214e71cSJoe   PetscCall(PetscOptionsRealArray("-cosine_coefficients", "Amplitude and frequency of cosine equation used in initialization", "ex2.c", options->cosine_coefficients, &d, NULL));
1918214e71cSJoe   PetscCall(PetscOptionsRealArray("-charges", "Species charges", "ex2.c", options->charges, &maxSpecies, NULL));
1928214e71cSJoe   PetscCall(PetscOptionsEnum("-em_type", "Type of electrostatic solver", "ex2.c", EMTypes, (PetscEnum)options->em, (PetscEnum *)&options->em, NULL));
193d0609cedSBarry Smith   PetscOptionsEnd();
194*84467f86SMatthew G. Knepley 
195*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventRegister("RhsX", TS_CLASSID, &options->RhsXEvent));
196*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventRegister("RhsV", TS_CLASSID, &options->RhsVEvent));
197*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventRegister("ESolve", TS_CLASSID, &options->ESolveEvent));
198*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventRegister("ETab", TS_CLASSID, &options->ETabEvent));
1993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
200b80bf5b1SJoe Pusztay }
201b80bf5b1SJoe Pusztay 
2028214e71cSJoe static PetscErrorCode SetupContext(DM dm, DM sw, AppCtx *user)
2038214e71cSJoe {
2048214e71cSJoe   PetscFunctionBeginUser;
2058214e71cSJoe   if (user->efield_monitor) {
2068214e71cSJoe     PetscDrawAxis axis_ef;
2078214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "monitor_efield", 0, 300, 400, 300, &user->drawef));
2088214e71cSJoe     PetscCall(PetscDrawSetSave(user->drawef, "ex9_Efield.png"));
2098214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->drawef));
2108214e71cSJoe     PetscCall(PetscDrawLGCreate(user->drawef, 1, &user->drawlg_ef));
2118214e71cSJoe     PetscCall(PetscDrawLGGetAxis(user->drawlg_ef, &axis_ef));
2128214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis_ef, "Electron Electric Field", "time", "E_max"));
2138214e71cSJoe     PetscCall(PetscDrawLGSetLimits(user->drawlg_ef, 0., user->steps * user->stepSize, -10., 0.));
2148214e71cSJoe     PetscCall(PetscDrawAxisSetLimits(axis_ef, 0., user->steps * user->stepSize, -10., 0.));
2158214e71cSJoe   }
2168214e71cSJoe   if (user->initial_monitor) {
2178214e71cSJoe     PetscDrawAxis axis1, axis2, axis3;
2188214e71cSJoe     PetscReal     dmboxlower[2], dmboxupper[2];
2198214e71cSJoe     PetscInt      dim, cStart, cEnd;
2208214e71cSJoe     PetscCall(DMGetDimension(sw, &dim));
2218214e71cSJoe     PetscCall(DMGetBoundingBox(dm, dmboxlower, dmboxupper));
2228214e71cSJoe     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
2238214e71cSJoe 
2248214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "monitor_initial_conditions_x", 0, 300, 400, 300, &user->drawic_x));
2258214e71cSJoe     PetscCall(PetscDrawSetSave(user->drawic_x, "ex9_ic_x.png"));
2268214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->drawic_x));
2276497c311SBarry Smith     PetscCall(PetscDrawHGCreate(user->drawic_x, (int)dim, &user->drawhgic_x));
2288214e71cSJoe     PetscCall(PetscDrawHGGetAxis(user->drawhgic_x, &axis1));
2296497c311SBarry Smith     PetscCall(PetscDrawHGSetNumberBins(user->drawhgic_x, (int)(cEnd - cStart)));
2308214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis1, "Initial X Distribution", "X", "counts"));
2318214e71cSJoe     PetscCall(PetscDrawAxisSetLimits(axis1, dmboxlower[0], dmboxupper[0], 0, 1500));
2328214e71cSJoe 
2338214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "monitor_initial_conditions_v", 400, 300, 400, 300, &user->drawic_v));
2348214e71cSJoe     PetscCall(PetscDrawSetSave(user->drawic_v, "ex9_ic_v.png"));
2358214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->drawic_v));
2366497c311SBarry Smith     PetscCall(PetscDrawHGCreate(user->drawic_v, (int)dim, &user->drawhgic_v));
2378214e71cSJoe     PetscCall(PetscDrawHGGetAxis(user->drawhgic_v, &axis2));
2388214e71cSJoe     PetscCall(PetscDrawHGSetNumberBins(user->drawhgic_v, 1000));
2398214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis2, "Initial V_x Distribution", "V", "counts"));
2408214e71cSJoe     PetscCall(PetscDrawAxisSetLimits(axis2, -1, 1, 0, 1500));
2418214e71cSJoe 
2428214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "monitor_initial_conditions_w", 800, 300, 400, 300, &user->drawic_w));
2438214e71cSJoe     PetscCall(PetscDrawSetSave(user->drawic_w, "ex9_ic_w.png"));
2448214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->drawic_w));
2456497c311SBarry Smith     PetscCall(PetscDrawHGCreate(user->drawic_w, (int)dim, &user->drawhgic_w));
2468214e71cSJoe     PetscCall(PetscDrawHGGetAxis(user->drawhgic_w, &axis3));
2478214e71cSJoe     PetscCall(PetscDrawHGSetNumberBins(user->drawhgic_w, 10));
2488214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis3, "Initial W Distribution", "weight", "counts"));
2498214e71cSJoe     PetscCall(PetscDrawAxisSetLimits(axis3, 0, 0.01, 0, 5000));
2508214e71cSJoe   }
2518214e71cSJoe   if (user->monitor_positions) {
2528214e71cSJoe     PetscDrawAxis axis;
2538214e71cSJoe 
2548214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "position_monitor_species1", 0, 0, 400, 300, &user->positionDraw));
2558214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->positionDraw));
2568214e71cSJoe     PetscCall(PetscDrawSPCreate(user->positionDraw, 10, &user->positionDrawSP));
2578214e71cSJoe     PetscCall(PetscDrawSPSetDimension(user->positionDrawSP, 1));
2588214e71cSJoe     PetscCall(PetscDrawSPGetAxis(user->positionDrawSP, &axis));
2598214e71cSJoe     PetscCall(PetscDrawSPReset(user->positionDrawSP));
2608214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis, "Particles", "x", "v"));
2618214e71cSJoe     PetscCall(PetscDrawSetSave(user->positionDraw, "ex9_pos.png"));
2628214e71cSJoe   }
2638214e71cSJoe   if (user->poisson_monitor) {
2648214e71cSJoe     PetscDrawAxis axis_E, axis_Rho, axis_Pot;
2658214e71cSJoe 
2668214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "Efield_monitor", 0, 0, 400, 300, &user->EDraw));
2678214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->EDraw));
2688214e71cSJoe     PetscCall(PetscDrawSPCreate(user->EDraw, 10, &user->EDrawSP));
2698214e71cSJoe     PetscCall(PetscDrawSPSetDimension(user->EDrawSP, 1));
2708214e71cSJoe     PetscCall(PetscDrawSPGetAxis(user->EDrawSP, &axis_E));
2718214e71cSJoe     PetscCall(PetscDrawSPReset(user->EDrawSP));
2728214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis_E, "Particles", "x", "E"));
2738214e71cSJoe     PetscCall(PetscDrawSetSave(user->EDraw, "ex9_E_spatial.png"));
2748214e71cSJoe 
2758214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "rho_monitor", 0, 0, 400, 300, &user->RhoDraw));
2768214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->RhoDraw));
2778214e71cSJoe     PetscCall(PetscDrawSPCreate(user->RhoDraw, 10, &user->RhoDrawSP));
2788214e71cSJoe     PetscCall(PetscDrawSPSetDimension(user->RhoDrawSP, 1));
2798214e71cSJoe     PetscCall(PetscDrawSPGetAxis(user->RhoDrawSP, &axis_Rho));
2808214e71cSJoe     PetscCall(PetscDrawSPReset(user->RhoDrawSP));
2818214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis_Rho, "Particles", "x", "rho"));
2828214e71cSJoe     PetscCall(PetscDrawSetSave(user->RhoDraw, "ex9_rho_spatial.png"));
2838214e71cSJoe 
2848214e71cSJoe     PetscCall(PetscDrawCreate(PETSC_COMM_WORLD, NULL, "potential_monitor", 0, 0, 400, 300, &user->PotDraw));
2858214e71cSJoe     PetscCall(PetscDrawSetFromOptions(user->PotDraw));
2868214e71cSJoe     PetscCall(PetscDrawSPCreate(user->PotDraw, 10, &user->PotDrawSP));
2878214e71cSJoe     PetscCall(PetscDrawSPSetDimension(user->PotDrawSP, 1));
2888214e71cSJoe     PetscCall(PetscDrawSPGetAxis(user->PotDrawSP, &axis_Pot));
2898214e71cSJoe     PetscCall(PetscDrawSPReset(user->PotDrawSP));
2908214e71cSJoe     PetscCall(PetscDrawAxisSetLabels(axis_Pot, "Particles", "x", "potential"));
2918214e71cSJoe     PetscCall(PetscDrawSetSave(user->PotDraw, "ex9_phi_spatial.png"));
2928214e71cSJoe   }
2938214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
2948214e71cSJoe }
2958214e71cSJoe 
2968214e71cSJoe static PetscErrorCode DestroyContext(AppCtx *user)
2978214e71cSJoe {
2988214e71cSJoe   PetscFunctionBeginUser;
2998214e71cSJoe   PetscCall(PetscDrawLGDestroy(&user->drawlg_ef));
3008214e71cSJoe   PetscCall(PetscDrawDestroy(&user->drawef));
3018214e71cSJoe   PetscCall(PetscDrawHGDestroy(&user->drawhgic_x));
3028214e71cSJoe   PetscCall(PetscDrawDestroy(&user->drawic_x));
3038214e71cSJoe   PetscCall(PetscDrawHGDestroy(&user->drawhgic_v));
3048214e71cSJoe   PetscCall(PetscDrawDestroy(&user->drawic_v));
3058214e71cSJoe   PetscCall(PetscDrawHGDestroy(&user->drawhgic_w));
3068214e71cSJoe   PetscCall(PetscDrawDestroy(&user->drawic_w));
3078214e71cSJoe   PetscCall(PetscDrawSPDestroy(&user->positionDrawSP));
3088214e71cSJoe   PetscCall(PetscDrawDestroy(&user->positionDraw));
3098214e71cSJoe 
3108214e71cSJoe   PetscCall(PetscDrawSPDestroy(&user->EDrawSP));
3118214e71cSJoe   PetscCall(PetscDrawDestroy(&user->EDraw));
3128214e71cSJoe   PetscCall(PetscDrawSPDestroy(&user->RhoDrawSP));
3138214e71cSJoe   PetscCall(PetscDrawDestroy(&user->RhoDraw));
3148214e71cSJoe   PetscCall(PetscDrawSPDestroy(&user->PotDrawSP));
3158214e71cSJoe   PetscCall(PetscDrawDestroy(&user->PotDraw));
3168214e71cSJoe 
3178214e71cSJoe   PetscCall(PetscBagDestroy(&user->bag));
3188214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
3198214e71cSJoe }
3208214e71cSJoe 
3218214e71cSJoe static PetscErrorCode CheckNonNegativeWeights(DM sw, AppCtx *user)
3228214e71cSJoe {
3238214e71cSJoe   const PetscScalar *w;
3248214e71cSJoe   PetscInt           Np;
3258214e71cSJoe 
3268214e71cSJoe   PetscFunctionBeginUser;
3278214e71cSJoe   if (!user->checkweights) PetscFunctionReturn(PETSC_SUCCESS);
3288214e71cSJoe   PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&w));
3298214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
3308214e71cSJoe   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]);
3318214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&w));
3328214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
3338214e71cSJoe }
3348214e71cSJoe 
3358214e71cSJoe static PetscErrorCode computeParticleMoments(DM sw, PetscReal moments[3], AppCtx *user)
3368214e71cSJoe {
3378214e71cSJoe   DM                 dm;
3388214e71cSJoe   const PetscReal   *coords;
3398214e71cSJoe   const PetscScalar *w;
3408214e71cSJoe   PetscReal          mom[3] = {0.0, 0.0, 0.0};
3418214e71cSJoe   PetscInt           cell, cStart, cEnd, dim;
3428214e71cSJoe 
3438214e71cSJoe   PetscFunctionBeginUser;
3448214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
3458214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &dm));
3468214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
3478214e71cSJoe   PetscCall(DMSwarmSortGetAccess(sw));
3488214e71cSJoe   PetscCall(DMSwarmGetField(sw, "velocity", NULL, NULL, (void **)&coords));
3498214e71cSJoe   PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&w));
3508214e71cSJoe   for (cell = cStart; cell < cEnd; ++cell) {
3518214e71cSJoe     PetscInt *pidx;
3528214e71cSJoe     PetscInt  Np, p, d;
3538214e71cSJoe 
3548214e71cSJoe     PetscCall(DMSwarmSortGetPointsPerCell(sw, cell, &Np, &pidx));
3558214e71cSJoe     for (p = 0; p < Np; ++p) {
3568214e71cSJoe       const PetscInt   idx = pidx[p];
3578214e71cSJoe       const PetscReal *c   = &coords[idx * dim];
3588214e71cSJoe 
3598214e71cSJoe       mom[0] += PetscRealPart(w[idx]);
3608214e71cSJoe       mom[1] += PetscRealPart(w[idx]) * c[0];
3618214e71cSJoe       for (d = 0; d < dim; ++d) mom[2] += PetscRealPart(w[idx]) * c[d] * c[d];
3628214e71cSJoe       //if (w[idx] < 0. ) PetscPrintf(PETSC_COMM_WORLD, "error, negative weight %" PetscInt_FMT " \n", idx);
3638214e71cSJoe     }
364*84467f86SMatthew G. Knepley     PetscCall(DMSwarmSortRestorePointsPerCell(sw, cell, &Np, &pidx));
3658214e71cSJoe   }
3668214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "velocity", NULL, NULL, (void **)&coords));
3678214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&w));
3688214e71cSJoe   PetscCall(DMSwarmSortRestoreAccess(sw));
3696a210b70SBarry Smith   PetscCallMPI(MPIU_Allreduce(mom, moments, 3, MPIU_REAL, MPI_SUM, PetscObjectComm((PetscObject)sw)));
3708214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
3718214e71cSJoe }
3728214e71cSJoe 
3738214e71cSJoe 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[])
3748214e71cSJoe {
3758214e71cSJoe   f0[0] = u[0];
3768214e71cSJoe }
3778214e71cSJoe 
3788214e71cSJoe 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[])
3798214e71cSJoe {
3808214e71cSJoe   f0[0] = x[0] * u[0];
3818214e71cSJoe }
3828214e71cSJoe 
3838214e71cSJoe 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[])
3848214e71cSJoe {
3858214e71cSJoe   PetscInt d;
3868214e71cSJoe 
3878214e71cSJoe   f0[0] = 0.0;
3888214e71cSJoe   for (d = 0; d < dim; ++d) f0[0] += PetscSqr(x[d]) * u[0];
3898214e71cSJoe }
3908214e71cSJoe 
3918214e71cSJoe static PetscErrorCode computeFEMMoments(DM dm, Vec u, PetscReal moments[3], AppCtx *user)
3928214e71cSJoe {
3938214e71cSJoe   PetscDS     prob;
3948214e71cSJoe   PetscScalar mom;
3958214e71cSJoe   PetscInt    field = 0;
3968214e71cSJoe 
3978214e71cSJoe   PetscFunctionBeginUser;
3988214e71cSJoe   PetscCall(DMGetDS(dm, &prob));
3998214e71cSJoe   PetscCall(PetscDSSetObjective(prob, field, &f0_1));
4008214e71cSJoe   PetscCall(DMPlexComputeIntegralFEM(dm, u, &mom, user));
4018214e71cSJoe   moments[0] = PetscRealPart(mom);
4028214e71cSJoe   PetscCall(PetscDSSetObjective(prob, field, &f0_x));
4038214e71cSJoe   PetscCall(DMPlexComputeIntegralFEM(dm, u, &mom, user));
4048214e71cSJoe   moments[1] = PetscRealPart(mom);
4058214e71cSJoe   PetscCall(PetscDSSetObjective(prob, field, &f0_r2));
4068214e71cSJoe   PetscCall(DMPlexComputeIntegralFEM(dm, u, &mom, user));
4078214e71cSJoe   moments[2] = PetscRealPart(mom);
4088214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
4098214e71cSJoe }
4108214e71cSJoe 
4118214e71cSJoe static PetscErrorCode MonitorEField(TS ts, PetscInt step, PetscReal t, Vec U, void *ctx)
4128214e71cSJoe {
4138214e71cSJoe   AppCtx    *user = (AppCtx *)ctx;
4148214e71cSJoe   DM         dm, sw;
4158214e71cSJoe   PetscReal *E;
4168214e71cSJoe   PetscReal  Enorm = 0., lgEnorm, lgEmax, sum = 0., Emax = 0., temp = 0., *weight, chargesum = 0.;
4178214e71cSJoe   PetscReal *x, *v;
4188214e71cSJoe   PetscInt  *species, dim, p, d, Np, cStart, cEnd;
4198214e71cSJoe   PetscReal  pmoments[3]; /* \int f, \int x f, \int r^2 f */
4208214e71cSJoe   PetscReal  fmoments[3]; /* \int \hat f, \int x \hat f, \int r^2 \hat f */
4218214e71cSJoe   Vec        rho;
4228214e71cSJoe 
4238214e71cSJoe   PetscFunctionBeginUser;
4248214e71cSJoe   if (step < 0) PetscFunctionReturn(PETSC_SUCCESS);
4258214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
4268214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &dm));
4278214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
4288214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
4298214e71cSJoe   PetscCall(DMSwarmSortGetAccess(sw));
4308214e71cSJoe   PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
4318214e71cSJoe   PetscCall(DMSwarmGetField(sw, "velocity", NULL, NULL, (void **)&v));
4328214e71cSJoe   PetscCall(DMSwarmGetField(sw, "E_field", NULL, NULL, (void **)&E));
4338214e71cSJoe   PetscCall(DMSwarmGetField(sw, "species", NULL, NULL, (void **)&species));
4348214e71cSJoe   PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&weight));
4358214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
4368214e71cSJoe 
4378214e71cSJoe   for (p = 0; p < Np; ++p) {
4388214e71cSJoe     for (d = 0; d < 1; ++d) {
4398214e71cSJoe       temp = PetscAbsReal(E[p * dim + d]);
4408214e71cSJoe       if (temp > Emax) Emax = temp;
4418214e71cSJoe     }
4428214e71cSJoe     Enorm += PetscSqrtReal(E[p * dim] * E[p * dim]);
4438214e71cSJoe     sum += E[p * dim];
4448214e71cSJoe     chargesum += user->charges[0] * weight[p];
4458214e71cSJoe   }
4468214e71cSJoe   lgEnorm = Enorm != 0 ? PetscLog10Real(Enorm) : -16.;
4478214e71cSJoe   lgEmax  = Emax != 0 ? PetscLog10Real(Emax) : -16.;
4488214e71cSJoe 
4498214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
4508214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "velocity", NULL, NULL, (void **)&v));
4518214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&weight));
4528214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "E_field", NULL, NULL, (void **)&E));
4538214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "species", NULL, NULL, (void **)&species));
4548214e71cSJoe 
4558214e71cSJoe   Parameter *param;
4568214e71cSJoe   PetscCall(PetscBagGetData(user->bag, (void **)&param));
4578214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "charges", &rho));
4588214e71cSJoe   if (user->em == EM_PRIMAL) {
4598214e71cSJoe     PetscCall(computeParticleMoments(sw, pmoments, user));
4608214e71cSJoe     PetscCall(computeFEMMoments(dm, rho, fmoments, user));
4618214e71cSJoe   } else if (user->em == EM_MIXED) {
4628214e71cSJoe     DM       potential_dm;
4638214e71cSJoe     IS       potential_IS;
4648214e71cSJoe     PetscInt fields = 1;
4658214e71cSJoe     PetscCall(DMCreateSubDM(dm, 1, &fields, &potential_IS, &potential_dm));
4668214e71cSJoe 
4678214e71cSJoe     PetscCall(computeParticleMoments(sw, pmoments, user));
4688214e71cSJoe     PetscCall(computeFEMMoments(potential_dm, rho, fmoments, user));
4698214e71cSJoe     PetscCall(DMDestroy(&potential_dm));
4708214e71cSJoe     PetscCall(ISDestroy(&potential_IS));
4718214e71cSJoe   }
4728214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "charges", &rho));
4738214e71cSJoe 
4748214e71cSJoe   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]));
4758214e71cSJoe   PetscCall(PetscDrawLGAddPoint(user->drawlg_ef, &t, &lgEmax));
4768214e71cSJoe   PetscCall(PetscDrawLGDraw(user->drawlg_ef));
4778214e71cSJoe   PetscCall(PetscDrawSave(user->drawef));
4788214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
4798214e71cSJoe }
4808214e71cSJoe 
4818214e71cSJoe PetscErrorCode MonitorInitialConditions(TS ts, PetscInt step, PetscReal t, Vec U, void *ctx)
4828214e71cSJoe {
4838214e71cSJoe   AppCtx            *user = (AppCtx *)ctx;
4848214e71cSJoe   DM                 dm, sw;
4858214e71cSJoe   const PetscScalar *u;
4868214e71cSJoe   PetscReal         *weight, *pos, *vel;
4878214e71cSJoe   PetscInt           dim, p, Np, cStart, cEnd;
4888214e71cSJoe 
4898214e71cSJoe   PetscFunctionBegin;
4908214e71cSJoe   if (step < 0) PetscFunctionReturn(PETSC_SUCCESS); /* -1 indicates interpolated solution */
4918214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
4928214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &dm));
4938214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
4948214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
4958214e71cSJoe   PetscCall(DMSwarmSortGetAccess(sw));
4968214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
4978214e71cSJoe 
4988214e71cSJoe   if (step == 0) {
4998214e71cSJoe     PetscCall(PetscDrawHGReset(user->drawhgic_x));
5008214e71cSJoe     PetscCall(PetscDrawHGGetDraw(user->drawhgic_x, &user->drawic_x));
5018214e71cSJoe     PetscCall(PetscDrawClear(user->drawic_x));
5028214e71cSJoe     PetscCall(PetscDrawFlush(user->drawic_x));
5038214e71cSJoe 
5048214e71cSJoe     PetscCall(PetscDrawHGReset(user->drawhgic_v));
5058214e71cSJoe     PetscCall(PetscDrawHGGetDraw(user->drawhgic_v, &user->drawic_v));
5068214e71cSJoe     PetscCall(PetscDrawClear(user->drawic_v));
5078214e71cSJoe     PetscCall(PetscDrawFlush(user->drawic_v));
5088214e71cSJoe 
5098214e71cSJoe     PetscCall(PetscDrawHGReset(user->drawhgic_w));
5108214e71cSJoe     PetscCall(PetscDrawHGGetDraw(user->drawhgic_w, &user->drawic_w));
5118214e71cSJoe     PetscCall(PetscDrawClear(user->drawic_w));
5128214e71cSJoe     PetscCall(PetscDrawFlush(user->drawic_w));
5138214e71cSJoe 
5148214e71cSJoe     PetscCall(VecGetArrayRead(U, &u));
5158214e71cSJoe     PetscCall(DMSwarmGetField(sw, "velocity", NULL, NULL, (void **)&vel));
5168214e71cSJoe     PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&weight));
5178214e71cSJoe     PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&pos));
5188214e71cSJoe 
5198214e71cSJoe     PetscCall(VecGetLocalSize(U, &Np));
5208214e71cSJoe     Np /= dim * 2;
5218214e71cSJoe     for (p = 0; p < Np; ++p) {
5228214e71cSJoe       PetscCall(PetscDrawHGAddValue(user->drawhgic_x, pos[p * dim]));
5238214e71cSJoe       PetscCall(PetscDrawHGAddValue(user->drawhgic_v, vel[p * dim]));
5248214e71cSJoe       PetscCall(PetscDrawHGAddValue(user->drawhgic_w, weight[p]));
5258214e71cSJoe     }
5268214e71cSJoe 
5278214e71cSJoe     PetscCall(VecRestoreArrayRead(U, &u));
5288214e71cSJoe     PetscCall(PetscDrawHGDraw(user->drawhgic_x));
5298214e71cSJoe     PetscCall(PetscDrawHGSave(user->drawhgic_x));
5308214e71cSJoe 
5318214e71cSJoe     PetscCall(PetscDrawHGDraw(user->drawhgic_v));
5328214e71cSJoe     PetscCall(PetscDrawHGSave(user->drawhgic_v));
5338214e71cSJoe 
5348214e71cSJoe     PetscCall(PetscDrawHGDraw(user->drawhgic_w));
5358214e71cSJoe     PetscCall(PetscDrawHGSave(user->drawhgic_w));
5368214e71cSJoe 
5378214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&pos));
5388214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "velocity", NULL, NULL, (void **)&vel));
5398214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&weight));
5408214e71cSJoe   }
5418214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
5428214e71cSJoe }
5438214e71cSJoe 
5448214e71cSJoe static PetscErrorCode MonitorPositions_2D(TS ts, PetscInt step, PetscReal t, Vec U, void *ctx)
5458214e71cSJoe {
5468214e71cSJoe   AppCtx         *user = (AppCtx *)ctx;
5478214e71cSJoe   DM              dm, sw;
5488214e71cSJoe   PetscScalar    *x, *v, *weight;
5498214e71cSJoe   PetscReal       lower[3], upper[3], speed;
5508214e71cSJoe   const PetscInt *s;
5518214e71cSJoe   PetscInt        dim, cStart, cEnd, c;
5528214e71cSJoe 
5538214e71cSJoe   PetscFunctionBeginUser;
5548214e71cSJoe   if (step > 0 && step % user->ostep == 0) {
5558214e71cSJoe     PetscCall(TSGetDM(ts, &sw));
5568214e71cSJoe     PetscCall(DMSwarmGetCellDM(sw, &dm));
5578214e71cSJoe     PetscCall(DMGetDimension(dm, &dim));
5588214e71cSJoe     PetscCall(DMGetBoundingBox(dm, lower, upper));
5598214e71cSJoe     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
5608214e71cSJoe     PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
5618214e71cSJoe     PetscCall(DMSwarmGetField(sw, "velocity", NULL, NULL, (void **)&v));
5628214e71cSJoe     PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&weight));
5638214e71cSJoe     PetscCall(DMSwarmGetField(sw, "species", NULL, NULL, (void **)&s));
5648214e71cSJoe     PetscCall(DMSwarmSortGetAccess(sw));
5658214e71cSJoe     PetscCall(PetscDrawSPReset(user->positionDrawSP));
5668214e71cSJoe     PetscCall(PetscDrawSPSetLimits(user->positionDrawSP, lower[0], upper[0], lower[1], upper[1]));
5678214e71cSJoe     PetscCall(PetscDrawSPSetLimits(user->positionDrawSP, lower[0], upper[0], -12, 12));
5688214e71cSJoe     for (c = 0; c < cEnd - cStart; ++c) {
5698214e71cSJoe       PetscInt *pidx, Npc, q;
5708214e71cSJoe       PetscCall(DMSwarmSortGetPointsPerCell(sw, c, &Npc, &pidx));
5718214e71cSJoe       for (q = 0; q < Npc; ++q) {
5728214e71cSJoe         const PetscInt p = pidx[q];
5738214e71cSJoe         if (s[p] == 0) {
5748214e71cSJoe           speed = PetscSqrtReal(PetscSqr(v[p * dim]) + PetscSqr(v[p * dim + 1]));
5758214e71cSJoe           if (dim == 1 || user->fake_1D) {
5768214e71cSJoe             PetscCall(PetscDrawSPAddPointColorized(user->positionDrawSP, &x[p * dim], &v[p * dim], &speed));
5778214e71cSJoe           } else {
5788214e71cSJoe             PetscCall(PetscDrawSPAddPointColorized(user->positionDrawSP, &x[p * dim], &x[p * dim + 1], &speed));
5798214e71cSJoe           }
5808214e71cSJoe         } else if (s[p] == 1) {
5818214e71cSJoe           PetscCall(PetscDrawSPAddPoint(user->positionDrawSP, &x[p * dim], &v[p * dim]));
5828214e71cSJoe         }
5838214e71cSJoe       }
584*84467f86SMatthew G. Knepley       PetscCall(DMSwarmSortRestorePointsPerCell(sw, c, &Npc, &pidx));
5858214e71cSJoe     }
5868214e71cSJoe     PetscCall(PetscDrawSPDraw(user->positionDrawSP, PETSC_TRUE));
5878214e71cSJoe     PetscCall(PetscDrawSave(user->positionDraw));
5888214e71cSJoe     PetscCall(DMSwarmSortRestoreAccess(sw));
5898214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
5908214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&weight));
5918214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "velocity", NULL, NULL, (void **)&v));
5928214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "species", NULL, NULL, (void **)&s));
5938214e71cSJoe   }
5948214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
5958214e71cSJoe }
5968214e71cSJoe 
5978214e71cSJoe static PetscErrorCode MonitorPoisson(TS ts, PetscInt step, PetscReal t, Vec U, void *ctx)
5988214e71cSJoe {
5998214e71cSJoe   AppCtx      *user = (AppCtx *)ctx;
6008214e71cSJoe   DM           dm, sw;
6018214e71cSJoe   PetscScalar *x, *E, *weight, *pot, *charges;
6028214e71cSJoe   PetscReal    lower[3], upper[3], xval;
6038214e71cSJoe   PetscInt     dim, cStart, cEnd, c;
6048214e71cSJoe 
6058214e71cSJoe   PetscFunctionBeginUser;
6068214e71cSJoe   if (step > 0 && step % user->ostep == 0) {
6078214e71cSJoe     PetscCall(TSGetDM(ts, &sw));
6088214e71cSJoe     PetscCall(DMSwarmGetCellDM(sw, &dm));
6098214e71cSJoe     PetscCall(DMGetDimension(dm, &dim));
6108214e71cSJoe     PetscCall(DMGetBoundingBox(dm, lower, upper));
6118214e71cSJoe     PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
6128214e71cSJoe 
6138214e71cSJoe     PetscCall(PetscDrawSPReset(user->RhoDrawSP));
6148214e71cSJoe     PetscCall(PetscDrawSPReset(user->EDrawSP));
6158214e71cSJoe     PetscCall(PetscDrawSPReset(user->PotDrawSP));
6168214e71cSJoe     PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
6178214e71cSJoe     PetscCall(DMSwarmGetField(sw, "E_field", NULL, NULL, (void **)&E));
6188214e71cSJoe     PetscCall(DMSwarmGetField(sw, "potential", NULL, NULL, (void **)&pot));
6198214e71cSJoe     PetscCall(DMSwarmGetField(sw, "charges", NULL, NULL, (void **)&charges));
6208214e71cSJoe     PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&weight));
6218214e71cSJoe 
6228214e71cSJoe     PetscCall(DMSwarmSortGetAccess(sw));
6238214e71cSJoe     for (c = 0; c < cEnd - cStart; ++c) {
6248214e71cSJoe       PetscReal Esum = 0.0;
6258214e71cSJoe       PetscInt *pidx, Npc, q;
6268214e71cSJoe       PetscCall(DMSwarmSortGetPointsPerCell(sw, c, &Npc, &pidx));
6278214e71cSJoe       for (q = 0; q < Npc; ++q) {
6288214e71cSJoe         const PetscInt p = pidx[q];
6298214e71cSJoe         Esum += E[p * dim];
6308214e71cSJoe       }
6318214e71cSJoe       xval = (c + 0.5) * ((upper[0] - lower[0]) / (cEnd - cStart));
6328214e71cSJoe       PetscCall(PetscDrawSPAddPoint(user->EDrawSP, &xval, &Esum));
633*84467f86SMatthew G. Knepley       PetscCall(DMSwarmSortRestorePointsPerCell(sw, c, &Npc, &pidx));
6348214e71cSJoe     }
6358214e71cSJoe     for (c = 0; c < (cEnd - cStart); ++c) {
6368214e71cSJoe       xval = (c + 0.5) * ((upper[0] - lower[0]) / (cEnd - cStart));
6378214e71cSJoe       PetscCall(PetscDrawSPAddPoint(user->RhoDrawSP, &xval, &charges[c]));
6388214e71cSJoe       PetscCall(PetscDrawSPAddPoint(user->PotDrawSP, &xval, &pot[c]));
6398214e71cSJoe     }
6408214e71cSJoe     PetscCall(PetscDrawSPDraw(user->RhoDrawSP, PETSC_TRUE));
6418214e71cSJoe     PetscCall(PetscDrawSave(user->RhoDraw));
6428214e71cSJoe     PetscCall(PetscDrawSPDraw(user->EDrawSP, PETSC_TRUE));
6438214e71cSJoe     PetscCall(PetscDrawSave(user->EDraw));
6448214e71cSJoe     PetscCall(PetscDrawSPDraw(user->PotDrawSP, PETSC_TRUE));
6458214e71cSJoe     PetscCall(PetscDrawSave(user->PotDraw));
6468214e71cSJoe     PetscCall(DMSwarmSortRestoreAccess(sw));
6478214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
6488214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "potential", NULL, NULL, (void **)&pot));
6498214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "charges", NULL, NULL, (void **)&charges));
6508214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&weight));
6518214e71cSJoe     PetscCall(DMSwarmRestoreField(sw, "E_field", NULL, NULL, (void **)&E));
6528214e71cSJoe   }
6538214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
6548214e71cSJoe }
6558214e71cSJoe 
6568214e71cSJoe static PetscErrorCode SetupParameters(MPI_Comm comm, AppCtx *ctx)
6578214e71cSJoe {
6588214e71cSJoe   PetscBag   bag;
6598214e71cSJoe   Parameter *p;
6608214e71cSJoe 
6618214e71cSJoe   PetscFunctionBeginUser;
6628214e71cSJoe   /* setup PETSc parameter bag */
6638214e71cSJoe   PetscCall(PetscBagGetData(ctx->bag, (void **)&p));
6648214e71cSJoe   PetscCall(PetscBagSetName(ctx->bag, "par", "Vlasov-Poisson Parameters"));
6658214e71cSJoe   bag = ctx->bag;
6668214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->v0, 1.0, "v0", "Velocity scale, m/s"));
6678214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->t0, 1.0, "t0", "Time scale, s"));
6688214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->x0, 1.0, "x0", "Space scale, m"));
6698214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->v0, 1.0, "phi0", "Potential scale, kg*m^2/A*s^3"));
6708214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->q0, 1.0, "q0", "Charge Scale, A*s"));
6718214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->m0, 1.0, "m0", "Mass Scale, kg"));
6728214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->epsi0, 1.0, "epsi0", "Permittivity of Free Space, kg"));
6738214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->kb, 1.0, "kb", "Boltzmann Constant, m^2 kg/s^2 K^1"));
6748214e71cSJoe 
6758214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->sigma, 1.0, "sigma", "Charge per unit area, C/m^3"));
6768214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->poissonNumber, 1.0, "poissonNumber", "Non-Dimensional Poisson Number"));
6778214e71cSJoe   PetscCall(PetscBagRegisterScalar(bag, &p->vlasovNumber, 1.0, "vlasovNumber", "Non-Dimensional Vlasov Number"));
6788214e71cSJoe   PetscCall(PetscBagSetFromOptions(bag));
6798214e71cSJoe   {
6808214e71cSJoe     PetscViewer       viewer;
6818214e71cSJoe     PetscViewerFormat format;
6828214e71cSJoe     PetscBool         flg;
6838214e71cSJoe 
684648c30bcSBarry Smith     PetscCall(PetscOptionsCreateViewer(comm, NULL, NULL, "-param_view", &viewer, &format, &flg));
6858214e71cSJoe     if (flg) {
6868214e71cSJoe       PetscCall(PetscViewerPushFormat(viewer, format));
6878214e71cSJoe       PetscCall(PetscBagView(bag, viewer));
6888214e71cSJoe       PetscCall(PetscViewerFlush(viewer));
6898214e71cSJoe       PetscCall(PetscViewerPopFormat(viewer));
6908214e71cSJoe       PetscCall(PetscViewerDestroy(&viewer));
6918214e71cSJoe     }
6928214e71cSJoe   }
6938214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
6948214e71cSJoe }
6958214e71cSJoe 
6968214e71cSJoe static PetscErrorCode CreateMesh(MPI_Comm comm, AppCtx *user, DM *dm)
697d71ae5a4SJacob Faibussowitsch {
698b80bf5b1SJoe Pusztay   PetscFunctionBeginUser;
6999566063dSJacob Faibussowitsch   PetscCall(DMCreate(comm, dm));
7009566063dSJacob Faibussowitsch   PetscCall(DMSetType(*dm, DMPLEX));
7019566063dSJacob Faibussowitsch   PetscCall(DMSetFromOptions(*dm));
7029566063dSJacob Faibussowitsch   PetscCall(DMViewFromOptions(*dm, NULL, "-dm_view"));
7033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
704b80bf5b1SJoe Pusztay }
705b80bf5b1SJoe Pusztay 
7068214e71cSJoe 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[])
7078214e71cSJoe {
7088214e71cSJoe   f0[0] = -constants[SIGMA];
7098214e71cSJoe }
7108214e71cSJoe 
711d71ae5a4SJacob 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[])
712d71ae5a4SJacob Faibussowitsch {
713b80bf5b1SJoe Pusztay   PetscInt d;
714ad540459SPierre Jolivet   for (d = 0; d < dim; ++d) f1[d] = u_x[d];
715b80bf5b1SJoe Pusztay }
716b80bf5b1SJoe Pusztay 
7178214e71cSJoe 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[])
718d71ae5a4SJacob Faibussowitsch {
719b80bf5b1SJoe Pusztay   PetscInt d;
720ad540459SPierre Jolivet   for (d = 0; d < dim; ++d) g3[d * dim + d] = 1.0;
721b80bf5b1SJoe Pusztay }
722b80bf5b1SJoe Pusztay 
7238214e71cSJoe static PetscErrorCode zero(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nc, PetscScalar *u, void *ctx)
724d71ae5a4SJacob Faibussowitsch {
7258214e71cSJoe   *u = 0.0;
7268214e71cSJoe   return PETSC_SUCCESS;
727b80bf5b1SJoe Pusztay }
728b80bf5b1SJoe Pusztay 
729b80bf5b1SJoe Pusztay /*
7308214e71cSJoe    /  I   -grad\ / q \ = /0\
7318214e71cSJoe    \-div    0  / \phi/   \f/
732b80bf5b1SJoe Pusztay */
7338214e71cSJoe 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[])
734d71ae5a4SJacob Faibussowitsch {
7358214e71cSJoe   for (PetscInt d = 0; d < dim; ++d) f0[d] += u[uOff[0] + d];
7368214e71cSJoe }
7378214e71cSJoe 
7388214e71cSJoe 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[])
7398214e71cSJoe {
7408214e71cSJoe   for (PetscInt d = 0; d < dim; ++d) f1[d * dim + d] = u[uOff[1]];
7418214e71cSJoe }
7428214e71cSJoe 
7438214e71cSJoe 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[])
7448214e71cSJoe {
7458214e71cSJoe   f0[0] += constants[SIGMA];
7468214e71cSJoe   for (PetscInt d = 0; d < dim; ++d) f0[0] += u_x[uOff_x[0] + d * dim + d];
7478214e71cSJoe }
7488214e71cSJoe 
7498214e71cSJoe /* Boundary residual. Dirichlet boundary for u means u_bdy=p*n */
7508214e71cSJoe 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[])
7518214e71cSJoe {
7528214e71cSJoe   for (PetscInt d = 0; d < dim; ++d) g0[d * dim + d] = 1.0;
7538214e71cSJoe }
7548214e71cSJoe 
7558214e71cSJoe 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[])
7568214e71cSJoe {
7578214e71cSJoe   for (PetscInt d = 0; d < dim; ++d) g2[d * dim + d] = 1.0;
7588214e71cSJoe }
7598214e71cSJoe 
7608214e71cSJoe 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[])
7618214e71cSJoe {
7628214e71cSJoe   for (PetscInt d = 0; d < dim; ++d) g1[d * dim + d] = 1.0;
7638214e71cSJoe }
7648214e71cSJoe 
7658214e71cSJoe static PetscErrorCode CreateFEM(DM dm, AppCtx *user)
7668214e71cSJoe {
7678214e71cSJoe   PetscFE   fephi, feq;
7688214e71cSJoe   PetscDS   ds;
7698214e71cSJoe   PetscBool simplex;
7708214e71cSJoe   PetscInt  dim;
7718214e71cSJoe 
7728214e71cSJoe   PetscFunctionBeginUser;
7738214e71cSJoe   PetscCall(DMGetDimension(dm, &dim));
7748214e71cSJoe   PetscCall(DMPlexIsSimplex(dm, &simplex));
7758214e71cSJoe   if (user->em == EM_MIXED) {
7768214e71cSJoe     DMLabel        label;
7778214e71cSJoe     const PetscInt id = 1;
7788214e71cSJoe 
7798214e71cSJoe     PetscCall(PetscFECreateDefault(PETSC_COMM_SELF, dim, dim, simplex, "field_", PETSC_DETERMINE, &feq));
7808214e71cSJoe     PetscCall(PetscObjectSetName((PetscObject)feq, "field"));
7818214e71cSJoe     PetscCall(PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, simplex, "potential_", PETSC_DETERMINE, &fephi));
7828214e71cSJoe     PetscCall(PetscObjectSetName((PetscObject)fephi, "potential"));
7838214e71cSJoe     PetscCall(PetscFECopyQuadrature(feq, fephi));
7848214e71cSJoe     PetscCall(DMSetField(dm, 0, NULL, (PetscObject)feq));
7858214e71cSJoe     PetscCall(DMSetField(dm, 1, NULL, (PetscObject)fephi));
7868214e71cSJoe     PetscCall(DMCreateDS(dm));
7878214e71cSJoe     PetscCall(PetscFEDestroy(&fephi));
7888214e71cSJoe     PetscCall(PetscFEDestroy(&feq));
7898214e71cSJoe 
7908214e71cSJoe     PetscCall(DMGetLabel(dm, "marker", &label));
7918214e71cSJoe     PetscCall(DMGetDS(dm, &ds));
7928214e71cSJoe 
7938214e71cSJoe     PetscCall(PetscDSSetResidual(ds, 0, f0_q, f1_q));
7948214e71cSJoe     PetscCall(PetscDSSetResidual(ds, 1, f0_phi_backgroundCharge, NULL));
7958214e71cSJoe     PetscCall(PetscDSSetJacobian(ds, 0, 0, g0_qq, NULL, NULL, NULL));
7968214e71cSJoe     PetscCall(PetscDSSetJacobian(ds, 0, 1, NULL, NULL, g2_qphi, NULL));
7978214e71cSJoe     PetscCall(PetscDSSetJacobian(ds, 1, 0, NULL, g1_phiq, NULL, NULL));
7988214e71cSJoe 
7998214e71cSJoe     PetscCall(DMAddBoundary(dm, DM_BC_ESSENTIAL, "wall", label, 1, &id, 0, 0, NULL, (void (*)(void))zero, NULL, NULL, NULL));
8008214e71cSJoe 
8018214e71cSJoe   } else if (user->em == EM_PRIMAL) {
8028214e71cSJoe     MatNullSpace nullsp;
8038214e71cSJoe     PetscCall(PetscFECreateDefault(PETSC_COMM_SELF, dim, 1, simplex, NULL, PETSC_DETERMINE, &fephi));
8048214e71cSJoe     PetscCall(PetscObjectSetName((PetscObject)fephi, "potential"));
8058214e71cSJoe     PetscCall(DMSetField(dm, 0, NULL, (PetscObject)fephi));
8068214e71cSJoe     PetscCall(DMCreateDS(dm));
8078214e71cSJoe     PetscCall(DMGetDS(dm, &ds));
8088214e71cSJoe     PetscCall(PetscDSSetResidual(ds, 0, ion_f0, laplacian_f1));
8098214e71cSJoe     PetscCall(PetscDSSetJacobian(ds, 0, 0, NULL, NULL, NULL, laplacian_g3));
8108214e71cSJoe     PetscCall(MatNullSpaceCreate(PetscObjectComm((PetscObject)dm), PETSC_TRUE, 0, NULL, &nullsp));
8118214e71cSJoe     PetscCall(PetscObjectCompose((PetscObject)fephi, "nullspace", (PetscObject)nullsp));
8128214e71cSJoe     PetscCall(MatNullSpaceDestroy(&nullsp));
8138214e71cSJoe     PetscCall(PetscFEDestroy(&fephi));
8148214e71cSJoe   }
8158214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
8168214e71cSJoe }
8178214e71cSJoe 
8188214e71cSJoe static PetscErrorCode CreatePoisson(DM dm, AppCtx *user)
8198214e71cSJoe {
8208214e71cSJoe   SNES         snes;
8218214e71cSJoe   Mat          J;
8228214e71cSJoe   MatNullSpace nullSpace;
8238214e71cSJoe 
8248214e71cSJoe   PetscFunctionBeginUser;
8258214e71cSJoe   PetscCall(CreateFEM(dm, user));
8268214e71cSJoe   PetscCall(SNESCreate(PetscObjectComm((PetscObject)dm), &snes));
8278214e71cSJoe   PetscCall(SNESSetOptionsPrefix(snes, "em_"));
8288214e71cSJoe   PetscCall(SNESSetDM(snes, dm));
8298214e71cSJoe   PetscCall(DMPlexSetSNESLocalFEM(dm, PETSC_FALSE, user));
8308214e71cSJoe   PetscCall(SNESSetFromOptions(snes));
8318214e71cSJoe 
8328214e71cSJoe   PetscCall(DMCreateMatrix(dm, &J));
8338214e71cSJoe   PetscCall(MatNullSpaceCreate(PetscObjectComm((PetscObject)dm), PETSC_TRUE, 0, NULL, &nullSpace));
8348214e71cSJoe   PetscCall(MatSetNullSpace(J, nullSpace));
8358214e71cSJoe   PetscCall(MatNullSpaceDestroy(&nullSpace));
8368214e71cSJoe   PetscCall(SNESSetJacobian(snes, J, J, NULL, NULL));
8378214e71cSJoe   PetscCall(MatDestroy(&J));
8388214e71cSJoe   user->snes = snes;
8398214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
8408214e71cSJoe }
8418214e71cSJoe 
8428214e71cSJoe PetscErrorCode PetscPDFPertubedConstant2D(const PetscReal x[], const PetscReal dummy[], PetscReal p[])
8438214e71cSJoe {
8448214e71cSJoe   p[0] = (1 + 0.01 * PetscCosReal(0.5 * x[0])) / (2 * PETSC_PI);
8458214e71cSJoe   p[1] = (1 + 0.01 * PetscCosReal(0.5 * x[1])) / (2 * PETSC_PI);
8468214e71cSJoe   return PETSC_SUCCESS;
8478214e71cSJoe }
8488214e71cSJoe PetscErrorCode PetscPDFPertubedConstant1D(const PetscReal x[], const PetscReal dummy[], PetscReal p[])
8498214e71cSJoe {
8508214e71cSJoe   p[0] = (1. + 0.01 * PetscCosReal(0.5 * x[0])) / (2 * PETSC_PI);
8518214e71cSJoe   return PETSC_SUCCESS;
8528214e71cSJoe }
8538214e71cSJoe 
8548214e71cSJoe PetscErrorCode PetscPDFCosine1D(const PetscReal x[], const PetscReal scale[], PetscReal p[])
8558214e71cSJoe {
8568214e71cSJoe   const PetscReal alpha = scale ? scale[0] : 0.0;
8578214e71cSJoe   const PetscReal k     = scale ? scale[1] : 1.;
8588214e71cSJoe   p[0]                  = (1 + alpha * PetscCosReal(k * x[0]));
8598214e71cSJoe   return PETSC_SUCCESS;
8608214e71cSJoe }
8618214e71cSJoe 
8628214e71cSJoe PetscErrorCode PetscPDFCosine2D(const PetscReal x[], const PetscReal scale[], PetscReal p[])
8638214e71cSJoe {
8648214e71cSJoe   const PetscReal alpha = scale ? scale[0] : 0.;
8658214e71cSJoe   const PetscReal k     = scale ? scale[0] : 1.;
8668214e71cSJoe   p[0]                  = (1 + alpha * PetscCosReal(k * (x[0] + x[1])));
8678214e71cSJoe   return PETSC_SUCCESS;
8688214e71cSJoe }
8698214e71cSJoe 
870*84467f86SMatthew G. Knepley static PetscErrorCode CreateVelocityDM(DM sw, DM *vdm)
8718214e71cSJoe {
872*84467f86SMatthew G. Knepley   PetscFunctionBegin;
873*84467f86SMatthew G. Knepley   PetscCall(DMCreate(PETSC_COMM_SELF, vdm));
874*84467f86SMatthew G. Knepley   PetscCall(DMSetType(*vdm, DMPLEX));
875*84467f86SMatthew G. Knepley   PetscCall(DMPlexSetOptionsPrefix(*vdm, "v"));
876*84467f86SMatthew G. Knepley   PetscCall(DMSetFromOptions(*vdm));
877*84467f86SMatthew G. Knepley   PetscCall(DMViewFromOptions(*vdm, NULL, "-dm_view"));
878*84467f86SMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
8798214e71cSJoe }
8808214e71cSJoe 
881*84467f86SMatthew G. Knepley static PetscErrorCode InitializeParticles_Centroid(DM sw, PetscBool force1D)
8828214e71cSJoe {
883*84467f86SMatthew G. Knepley   DM_Swarm  *swarm = (DM_Swarm *)sw->data;
884*84467f86SMatthew G. Knepley   DM         xdm, vdm;
885*84467f86SMatthew G. Knepley   PetscReal  vmin[3], vmax[3];
886*84467f86SMatthew G. Knepley   PetscReal *x, *v;
887*84467f86SMatthew G. Knepley   PetscInt  *species, *cellid;
888*84467f86SMatthew G. Knepley   PetscInt   dim, xcStart, xcEnd, vcStart, vcEnd, Ns, Np, Npc, debug;
8898214e71cSJoe   PetscBool  flg;
890*84467f86SMatthew G. Knepley   MPI_Comm   comm;
8918214e71cSJoe 
8928214e71cSJoe   PetscFunctionBegin;
893*84467f86SMatthew G. Knepley   PetscCall(PetscObjectGetComm((PetscObject)sw, &comm));
894*84467f86SMatthew G. Knepley 
895*84467f86SMatthew G. Knepley   PetscOptionsBegin(comm, "", "DMSwarm Options", "DMSWARM");
8968214e71cSJoe   PetscCall(DMSwarmGetNumSpecies(sw, &Ns));
8978214e71cSJoe   PetscCall(PetscOptionsInt("-dm_swarm_num_species", "The number of species", "DMSwarmSetNumSpecies", Ns, &Ns, &flg));
8988214e71cSJoe   if (flg) PetscCall(DMSwarmSetNumSpecies(sw, Ns));
899*84467f86SMatthew G. Knepley   PetscCall(PetscOptionsBoundedInt("-dm_swarm_print_coords", "Debug output level for particle coordinate computations", "InitializeParticles", 0, &swarm->printCoords, NULL, 0));
900*84467f86SMatthew G. Knepley   PetscCall(PetscOptionsBoundedInt("-dm_swarm_print_weights", "Debug output level for particle weight computations", "InitializeWeights", 0, &swarm->printWeights, NULL, 0));
9018214e71cSJoe   PetscOptionsEnd();
902*84467f86SMatthew G. Knepley   debug = swarm->printCoords;
9038214e71cSJoe 
9048214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
905*84467f86SMatthew G. Knepley   PetscCall(DMSwarmGetCellDM(sw, &xdm));
906*84467f86SMatthew G. Knepley   PetscCall(DMPlexGetHeightStratum(xdm, 0, &xcStart, &xcEnd));
9078214e71cSJoe 
908*84467f86SMatthew G. Knepley   PetscCall(PetscObjectQuery((PetscObject)sw, "__vdm__", (PetscObject *)&vdm));
909*84467f86SMatthew G. Knepley   if (!vdm) {
910*84467f86SMatthew G. Knepley     PetscCall(CreateVelocityDM(sw, &vdm));
911*84467f86SMatthew G. Knepley     PetscCall(PetscObjectCompose((PetscObject)sw, "__vdm__", (PetscObject)vdm));
912*84467f86SMatthew G. Knepley     PetscCall(DMDestroy(&vdm));
913*84467f86SMatthew G. Knepley     PetscCall(PetscObjectQuery((PetscObject)sw, "__vdm__", (PetscObject *)&vdm));
914*84467f86SMatthew G. Knepley   }
915*84467f86SMatthew G. Knepley   PetscCall(DMPlexGetHeightStratum(vdm, 0, &vcStart, &vcEnd));
9168214e71cSJoe 
917*84467f86SMatthew G. Knepley   // One particle per centroid on the tensor product grid
918*84467f86SMatthew G. Knepley   Npc = (vcEnd - vcStart) * Ns;
919*84467f86SMatthew G. Knepley   Np  = (xcEnd - xcStart) * Npc;
9208214e71cSJoe   PetscCall(DMSwarmSetLocalSizes(sw, Np, 0));
921*84467f86SMatthew G. Knepley   if (debug) {
922*84467f86SMatthew G. Knepley     PetscInt gNp;
923*84467f86SMatthew G. Knepley     PetscCallMPI(MPIU_Allreduce(&Np, &gNp, 1, MPIU_INT, MPIU_SUM, comm));
924*84467f86SMatthew G. Knepley     PetscCall(PetscPrintf(comm, "Global Np = %" PetscInt_FMT "\n", gNp));
9258214e71cSJoe   }
9268214e71cSJoe 
927*84467f86SMatthew G. Knepley   // Set species and cellid
928*84467f86SMatthew G. Knepley   PetscCall(DMSwarmGetField(sw, "species", NULL, NULL, (void **)&species));
929*84467f86SMatthew G. Knepley   PetscCall(DMSwarmGetField(sw, DMSwarmPICField_cellid, NULL, NULL, (void **)&cellid));
930*84467f86SMatthew G. Knepley   for (PetscInt c = 0, p = 0; c < xcEnd - xcStart; ++c) {
931*84467f86SMatthew G. Knepley     for (PetscInt s = 0; s < Ns; ++s) {
932*84467f86SMatthew G. Knepley       for (PetscInt q = 0; q < Npc / Ns; ++q, ++p) {
933*84467f86SMatthew G. Knepley         species[p] = s;
934*84467f86SMatthew G. Knepley         cellid[p]  = c;
935*84467f86SMatthew G. Knepley       }
936*84467f86SMatthew G. Knepley     }
937*84467f86SMatthew G. Knepley   }
938*84467f86SMatthew G. Knepley   PetscCall(DMSwarmRestoreField(sw, "species", NULL, NULL, (void **)&species));
939*84467f86SMatthew G. Knepley   PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_cellid, NULL, NULL, (void **)&cellid));
940*84467f86SMatthew G. Knepley 
941*84467f86SMatthew G. Knepley   // Set particle coordinates
9428214e71cSJoe   PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
9438214e71cSJoe   PetscCall(DMSwarmGetField(sw, "velocity", NULL, NULL, (void **)&v));
9448214e71cSJoe   PetscCall(DMSwarmSortGetAccess(sw));
945*84467f86SMatthew G. Knepley   PetscCall(DMGetBoundingBox(vdm, vmin, vmax));
946*84467f86SMatthew G. Knepley   PetscCall(DMGetCoordinatesLocalSetUp(xdm));
947*84467f86SMatthew G. Knepley   for (PetscInt c = 0; c < xcEnd - xcStart; ++c) {
948*84467f86SMatthew G. Knepley     const PetscInt cell = c + xcStart;
9498214e71cSJoe     PetscInt      *pidx, Npc;
9508214e71cSJoe     PetscReal      centroid[3], volume;
9518214e71cSJoe 
9528214e71cSJoe     PetscCall(DMSwarmSortGetPointsPerCell(sw, c, &Npc, &pidx));
953*84467f86SMatthew G. Knepley     PetscCall(DMPlexComputeCellGeometryFVM(xdm, cell, &volume, centroid, NULL));
954*84467f86SMatthew G. Knepley     for (PetscInt s = 0; s < Ns; ++s) {
955*84467f86SMatthew G. Knepley       for (PetscInt q = 0; q < Npc / Ns; ++q) {
956*84467f86SMatthew G. Knepley         const PetscInt p = pidx[q * Ns + s];
9578214e71cSJoe 
958*84467f86SMatthew G. Knepley         for (PetscInt d = 0; d < dim; ++d) {
9598214e71cSJoe           x[p * dim + d] = centroid[d];
960*84467f86SMatthew G. Knepley           v[p * dim + d] = vmin[0] + (q + 0.5) * ((vmax[0] - vmin[0]) / (Npc / Ns));
961*84467f86SMatthew G. Knepley           if (force1D && d > 0) v[p * dim + d] = 0.;
9628214e71cSJoe         }
9638214e71cSJoe       }
9648214e71cSJoe     }
965*84467f86SMatthew G. Knepley     PetscCall(DMSwarmSortRestorePointsPerCell(sw, c, &Npc, &pidx));
9668214e71cSJoe   }
9678214e71cSJoe   PetscCall(DMSwarmSortRestoreAccess(sw));
9688214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&x));
9698214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "velocity", NULL, NULL, (void **)&v));
970*84467f86SMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
971*84467f86SMatthew G. Knepley }
972*84467f86SMatthew G. Knepley 
973*84467f86SMatthew G. Knepley /*
974*84467f86SMatthew G. Knepley   InitializeWeights - Compute weight for each local particle
975*84467f86SMatthew G. Knepley 
976*84467f86SMatthew G. Knepley   Input Parameters:
977*84467f86SMatthew G. Knepley + sw          - The `DMSwarm`
978*84467f86SMatthew G. Knepley . totalWeight - The sum of all particle weights
979*84467f86SMatthew G. Knepley . force1D     - Flag to treat the problem as 1D
980*84467f86SMatthew G. Knepley . func        - The PDF for the particle spatial distribution
981*84467f86SMatthew G. Knepley - param       - The PDF parameters
982*84467f86SMatthew G. Knepley 
983*84467f86SMatthew G. Knepley   Notes:
984*84467f86SMatthew G. Knepley   The PDF for velocity is assumed to be a Gaussian
985*84467f86SMatthew G. Knepley 
986*84467f86SMatthew G. Knepley   The particle weights are returned in the `w_q` field of `sw`.
987*84467f86SMatthew G. Knepley */
988*84467f86SMatthew G. Knepley static PetscErrorCode InitializeWeights(DM sw, PetscReal totalWeight, PetscBool force1D, PetscProbFunc func, const PetscReal param[])
989*84467f86SMatthew G. Knepley {
990*84467f86SMatthew G. Knepley   DM               xdm, vdm;
991*84467f86SMatthew G. Knepley   PetscScalar     *weight;
992*84467f86SMatthew G. Knepley   PetscQuadrature  xquad;
993*84467f86SMatthew G. Knepley   const PetscReal *xq, *xwq;
994*84467f86SMatthew G. Knepley   const PetscInt   order = 5;
995*84467f86SMatthew G. Knepley   PetscReal       *xqd   = NULL, xi0[3];
996*84467f86SMatthew G. Knepley   PetscReal        xwtot = 0., pwtot = 0.;
997*84467f86SMatthew G. Knepley   PetscInt         xNq;
998*84467f86SMatthew G. Knepley   PetscInt         dim, Ns, xcStart, xcEnd, vcStart, vcEnd, debug = ((DM_Swarm *)sw->data)->printWeights;
999*84467f86SMatthew G. Knepley   MPI_Comm         comm;
1000*84467f86SMatthew G. Knepley   PetscMPIInt      rank;
1001*84467f86SMatthew G. Knepley 
1002*84467f86SMatthew G. Knepley   PetscFunctionBegin;
1003*84467f86SMatthew G. Knepley   PetscCall(PetscObjectGetComm((PetscObject)sw, &comm));
1004*84467f86SMatthew G. Knepley   PetscCallMPI(MPI_Comm_rank(comm, &rank));
1005*84467f86SMatthew G. Knepley   PetscCall(DMGetDimension(sw, &dim));
1006*84467f86SMatthew G. Knepley   PetscCall(DMSwarmGetCellDM(sw, &xdm));
1007*84467f86SMatthew G. Knepley   PetscCall(DMSwarmGetNumSpecies(sw, &Ns));
1008*84467f86SMatthew G. Knepley   PetscCall(DMPlexGetHeightStratum(xdm, 0, &xcStart, &xcEnd));
1009*84467f86SMatthew G. Knepley   PetscCall(PetscObjectQuery((PetscObject)sw, "__vdm__", (PetscObject *)&vdm));
1010*84467f86SMatthew G. Knepley   PetscCall(DMPlexGetHeightStratum(vdm, 0, &vcStart, &vcEnd));
1011*84467f86SMatthew G. Knepley 
1012*84467f86SMatthew G. Knepley   // Setup Quadrature for spatial and velocity weight calculations
1013*84467f86SMatthew G. Knepley   if (force1D) PetscCall(PetscDTGaussTensorQuadrature(1, 1, order, -1.0, 1.0, &xquad));
1014*84467f86SMatthew G. Knepley   else PetscCall(PetscDTGaussTensorQuadrature(dim, 1, order, -1.0, 1.0, &xquad));
1015*84467f86SMatthew G. Knepley   PetscCall(PetscQuadratureGetData(xquad, NULL, NULL, &xNq, &xq, &xwq));
1016*84467f86SMatthew G. Knepley   if (force1D) {
1017*84467f86SMatthew G. Knepley     PetscCall(PetscCalloc1(xNq * dim, &xqd));
1018*84467f86SMatthew G. Knepley     for (PetscInt q = 0; q < xNq; ++q) xqd[q * dim] = xq[q];
1019*84467f86SMatthew G. Knepley   }
1020*84467f86SMatthew G. Knepley   for (PetscInt d = 0; d < dim; ++d) xi0[d] = -1.0;
1021*84467f86SMatthew G. Knepley 
1022*84467f86SMatthew G. Knepley   // Integrate the density function to get the weights of particles in each cell
1023*84467f86SMatthew G. Knepley   PetscCall(DMGetCoordinatesLocalSetUp(vdm));
1024*84467f86SMatthew G. Knepley   PetscCall(DMSwarmSortGetAccess(sw));
1025*84467f86SMatthew G. Knepley   PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&weight));
1026*84467f86SMatthew G. Knepley   for (PetscInt c = xcStart; c < xcEnd; ++c) {
1027*84467f86SMatthew G. Knepley     PetscReal          xv0[3], xJ[9], xinvJ[9], xdetJ, xqr[3], xden, xw = 0.;
1028*84467f86SMatthew G. Knepley     PetscInt          *pidx, Npc;
1029*84467f86SMatthew G. Knepley     PetscInt           xNc;
1030*84467f86SMatthew G. Knepley     const PetscScalar *xarray;
1031*84467f86SMatthew G. Knepley     PetscScalar       *xcoords = NULL;
1032*84467f86SMatthew G. Knepley     PetscBool          xisDG;
1033*84467f86SMatthew G. Knepley 
1034*84467f86SMatthew G. Knepley     PetscCall(DMPlexGetCellCoordinates(xdm, c, &xisDG, &xNc, &xarray, &xcoords));
1035*84467f86SMatthew G. Knepley     PetscCall(DMSwarmSortGetPointsPerCell(sw, c, &Npc, &pidx));
1036*84467f86SMatthew G. Knepley     PetscCheck(Npc == (vcEnd - vcStart) * Ns, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Number of particles %" PetscInt_FMT " in cell (rank %d) != %" PetscInt_FMT " number of velocity vertices", Npc, rank, (vcEnd - vcStart) * Ns);
1037*84467f86SMatthew G. Knepley     PetscCall(DMPlexComputeCellGeometryFEM(xdm, c, NULL, xv0, xJ, xinvJ, &xdetJ));
1038*84467f86SMatthew G. Knepley     for (PetscInt q = 0; q < xNq; ++q) {
1039*84467f86SMatthew G. Knepley       // Transform quadrature points from ref space to real space
1040*84467f86SMatthew G. Knepley       if (force1D) CoordinatesRefToReal(dim, dim, xi0, xv0, xJ, &xqd[q * dim], xqr);
1041*84467f86SMatthew G. Knepley       else CoordinatesRefToReal(dim, dim, xi0, xv0, xJ, &xq[q * dim], xqr);
1042*84467f86SMatthew G. Knepley       // Get probability density at quad point
1043*84467f86SMatthew G. Knepley       //   No need to scale xqr since PDF will be periodic
1044*84467f86SMatthew G. Knepley       PetscCall((*func)(xqr, param, &xden));
1045*84467f86SMatthew G. Knepley       if (force1D) xdetJ = xJ[0]; // Only want x contribution
1046*84467f86SMatthew G. Knepley       xw += xden * (xwq[q] * xdetJ);
1047*84467f86SMatthew G. Knepley     }
1048*84467f86SMatthew G. Knepley     xwtot += xw;
1049*84467f86SMatthew G. Knepley     if (debug) {
1050*84467f86SMatthew G. Knepley       IS              globalOrdering;
1051*84467f86SMatthew G. Knepley       const PetscInt *ordering;
1052*84467f86SMatthew G. Knepley 
1053*84467f86SMatthew G. Knepley       PetscCall(DMPlexGetCellNumbering(xdm, &globalOrdering));
1054*84467f86SMatthew G. Knepley       PetscCall(ISGetIndices(globalOrdering, &ordering));
1055*84467f86SMatthew G. Knepley       PetscCall(PetscSynchronizedPrintf(comm, "c:%" PetscInt_FMT " [x_a,x_b] = %1.15f,%1.15f -> cell weight = %1.15f\n", ordering[c], (double)PetscRealPart(xcoords[0]), (double)PetscRealPart(xcoords[2]), (double)xw));
1056*84467f86SMatthew G. Knepley       PetscCall(ISRestoreIndices(globalOrdering, &ordering));
1057*84467f86SMatthew G. Knepley     }
1058*84467f86SMatthew G. Knepley     // Set weights to be Gaussian in velocity cells
1059*84467f86SMatthew G. Knepley     for (PetscInt vc = vcStart; vc < vcEnd; ++vc) {
1060*84467f86SMatthew G. Knepley       const PetscInt     p  = pidx[vc * Ns + 0];
1061*84467f86SMatthew G. Knepley       PetscReal          vw = 0.;
1062*84467f86SMatthew G. Knepley       PetscInt           vNc;
1063*84467f86SMatthew G. Knepley       const PetscScalar *varray;
1064*84467f86SMatthew G. Knepley       PetscScalar       *vcoords = NULL;
1065*84467f86SMatthew G. Knepley       PetscBool          visDG;
1066*84467f86SMatthew G. Knepley 
1067*84467f86SMatthew G. Knepley       PetscCall(DMPlexGetCellCoordinates(vdm, vc, &visDG, &vNc, &varray, &vcoords));
1068*84467f86SMatthew G. Knepley       // TODO: Fix 2 stream Ask Joe
1069*84467f86SMatthew G. Knepley       //   Two stream function from 1/2pi v^2 e^(-v^2/2)
1070*84467f86SMatthew G. Knepley       //   vw = 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.)));
1071*84467f86SMatthew G. Knepley       vw = 0.5 * (PetscErfReal(vcoords[1] / PetscSqrtReal(2.)) - PetscErfReal(vcoords[0] / PetscSqrtReal(2.)));
1072*84467f86SMatthew G. Knepley 
1073*84467f86SMatthew G. Knepley       weight[p] = totalWeight * vw * xw;
1074*84467f86SMatthew G. Knepley       pwtot += weight[p];
1075*84467f86SMatthew G. Knepley       PetscCheck(weight[p] <= 1., PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Particle %" PetscInt_FMT " weight exceeeded 1: %g, %g, %g", p, xw, vw, totalWeight);
1076*84467f86SMatthew G. Knepley       PetscCall(DMPlexRestoreCellCoordinates(vdm, vc, &visDG, &vNc, &varray, &vcoords));
1077*84467f86SMatthew G. Knepley       if (debug > 1) PetscCall(PetscPrintf(comm, "particle %" PetscInt_FMT ": %g, vw: %g xw: %g\n", p, weight[p], vw, xw));
1078*84467f86SMatthew G. Knepley     }
1079*84467f86SMatthew G. Knepley     PetscCall(DMPlexRestoreCellCoordinates(xdm, c, &xisDG, &xNc, &xarray, &xcoords));
1080*84467f86SMatthew G. Knepley     PetscCall(DMSwarmSortRestorePointsPerCell(sw, c, &Npc, &pidx));
1081*84467f86SMatthew G. Knepley   }
1082*84467f86SMatthew G. Knepley   PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&weight));
1083*84467f86SMatthew G. Knepley   PetscCall(DMSwarmSortRestoreAccess(sw));
1084*84467f86SMatthew G. Knepley   PetscCall(PetscQuadratureDestroy(&xquad));
1085*84467f86SMatthew G. Knepley   if (force1D) PetscCall(PetscFree(xqd));
1086*84467f86SMatthew G. Knepley 
1087*84467f86SMatthew G. Knepley   if (debug) {
1088*84467f86SMatthew G. Knepley     PetscReal wtot[2] = {pwtot, xwtot}, gwtot[2];
1089*84467f86SMatthew G. Knepley 
1090*84467f86SMatthew G. Knepley     PetscCall(PetscSynchronizedFlush(comm, NULL));
1091*84467f86SMatthew G. Knepley     PetscCallMPI(MPIU_Allreduce(wtot, gwtot, 2, MPIU_REAL, MPIU_SUM, PETSC_COMM_WORLD));
1092*84467f86SMatthew G. Knepley     PetscCall(PetscPrintf(comm, "particle weight sum = %1.10f cell weight sum = %1.10f\n", (double)gwtot[0], (double)gwtot[1]));
1093*84467f86SMatthew G. Knepley   }
1094*84467f86SMatthew G. Knepley   PetscFunctionReturn(PETSC_SUCCESS);
1095*84467f86SMatthew G. Knepley }
1096*84467f86SMatthew G. Knepley 
1097*84467f86SMatthew G. Knepley static PetscErrorCode InitializeParticles_PerturbedWeights(DM sw, AppCtx *user)
1098*84467f86SMatthew G. Knepley {
1099*84467f86SMatthew G. Knepley   PetscReal scale[2] = {user->cosine_coefficients[0], user->cosine_coefficients[1]};
1100*84467f86SMatthew G. Knepley 
1101*84467f86SMatthew G. Knepley   PetscFunctionBegin;
1102*84467f86SMatthew G. Knepley   PetscCall(InitializeParticles_Centroid(sw, user->fake_1D));
1103*84467f86SMatthew G. Knepley   PetscCall(InitializeWeights(sw, user->totalWeight, user->fake_1D, user->fake_1D ? PetscPDFCosine1D : PetscPDFCosine2D, scale));
11048214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
11058214e71cSJoe }
11068214e71cSJoe 
11078214e71cSJoe static PetscErrorCode InitializeConstants(DM sw, AppCtx *user)
11088214e71cSJoe {
11098214e71cSJoe   DM         dm;
11108214e71cSJoe   PetscInt  *species;
11118214e71cSJoe   PetscReal *weight, totalCharge = 0., totalWeight = 0., gmin[3], gmax[3], global_charge, global_weight;
11128214e71cSJoe   PetscInt   Np, dim;
11138214e71cSJoe 
11148214e71cSJoe   PetscFunctionBegin;
11158214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &dm));
11168214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
11178214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
11188214e71cSJoe   PetscCall(DMGetBoundingBox(dm, gmin, gmax));
11198214e71cSJoe   PetscCall(DMSwarmGetField(sw, "w_q", NULL, NULL, (void **)&weight));
11208214e71cSJoe   PetscCall(DMSwarmGetField(sw, "species", NULL, NULL, (void **)&species));
11218214e71cSJoe   for (PetscInt p = 0; p < Np; ++p) {
11228214e71cSJoe     totalWeight += weight[p];
11238214e71cSJoe     totalCharge += user->charges[species[p]] * weight[p];
11248214e71cSJoe   }
11258214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "w_q", NULL, NULL, (void **)&weight));
11268214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "species", NULL, NULL, (void **)&species));
11278214e71cSJoe   {
11288214e71cSJoe     Parameter *param;
11298214e71cSJoe     PetscReal  Area;
11308214e71cSJoe 
11318214e71cSJoe     PetscCall(PetscBagGetData(user->bag, (void **)&param));
11328214e71cSJoe     switch (dim) {
11338214e71cSJoe     case 1:
11348214e71cSJoe       Area = (gmax[0] - gmin[0]);
11358214e71cSJoe       break;
11368214e71cSJoe     case 2:
11378214e71cSJoe       if (user->fake_1D) {
11388214e71cSJoe         Area = (gmax[0] - gmin[0]);
11398214e71cSJoe       } else {
11408214e71cSJoe         Area = (gmax[0] - gmin[0]) * (gmax[1] - gmin[1]);
11418214e71cSJoe       }
11428214e71cSJoe       break;
11438214e71cSJoe     case 3:
11448214e71cSJoe       Area = (gmax[0] - gmin[0]) * (gmax[1] - gmin[1]) * (gmax[2] - gmin[2]);
11458214e71cSJoe       break;
11468214e71cSJoe     default:
11478214e71cSJoe       SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Dimension %" PetscInt_FMT " not supported", dim);
11488214e71cSJoe     }
1149462c564dSBarry Smith     PetscCallMPI(MPIU_Allreduce(&totalWeight, &global_weight, 1, MPIU_REAL, MPIU_SUM, PETSC_COMM_WORLD));
1150462c564dSBarry Smith     PetscCallMPI(MPIU_Allreduce(&totalCharge, &global_charge, 1, MPIU_REAL, MPIU_SUM, PETSC_COMM_WORLD));
11518214e71cSJoe     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));
11528214e71cSJoe     param->sigma = PetscAbsReal(global_charge / (Area));
11538214e71cSJoe 
11548214e71cSJoe     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "sigma: %g\n", (double)param->sigma));
11558214e71cSJoe     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,
11568214e71cSJoe                           (double)param->vlasovNumber));
11578214e71cSJoe   }
11588214e71cSJoe   /* Setup Constants */
11598214e71cSJoe   {
11608214e71cSJoe     PetscDS    ds;
11618214e71cSJoe     Parameter *param;
11628214e71cSJoe     PetscCall(PetscBagGetData(user->bag, (void **)&param));
11638214e71cSJoe     PetscScalar constants[NUM_CONSTANTS];
11648214e71cSJoe     constants[SIGMA]   = param->sigma;
11658214e71cSJoe     constants[V0]      = param->v0;
11668214e71cSJoe     constants[T0]      = param->t0;
11678214e71cSJoe     constants[X0]      = param->x0;
11688214e71cSJoe     constants[M0]      = param->m0;
11698214e71cSJoe     constants[Q0]      = param->q0;
11708214e71cSJoe     constants[PHI0]    = param->phi0;
11718214e71cSJoe     constants[POISSON] = param->poissonNumber;
11728214e71cSJoe     constants[VLASOV]  = param->vlasovNumber;
11738214e71cSJoe     PetscCall(DMGetDS(dm, &ds));
11748214e71cSJoe     PetscCall(PetscDSSetConstants(ds, NUM_CONSTANTS, constants));
11758214e71cSJoe   }
11768214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
11778214e71cSJoe }
11788214e71cSJoe 
11798214e71cSJoe static PetscErrorCode InitializeVelocities_Fake1D(DM sw, AppCtx *user)
11808214e71cSJoe {
11818214e71cSJoe   DM         dm;
11828214e71cSJoe   PetscReal *v;
11838214e71cSJoe   PetscInt  *species, cStart, cEnd;
11848214e71cSJoe   PetscInt   dim, Np;
11858214e71cSJoe 
11868214e71cSJoe   PetscFunctionBegin;
11878214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
11888214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
11898214e71cSJoe   PetscCall(DMSwarmGetField(sw, "velocity", NULL, NULL, (void **)&v));
11908214e71cSJoe   PetscCall(DMSwarmGetField(sw, "species", NULL, NULL, (void **)&species));
11918214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &dm));
11928214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
11938214e71cSJoe   PetscRandom rnd;
11948214e71cSJoe   PetscCall(PetscRandomCreate(PetscObjectComm((PetscObject)sw), &rnd));
11958214e71cSJoe   PetscCall(PetscRandomSetInterval(rnd, 0, 1.));
11968214e71cSJoe   PetscCall(PetscRandomSetFromOptions(rnd));
11978214e71cSJoe 
11988214e71cSJoe   for (PetscInt p = 0; p < Np; ++p) {
11998214e71cSJoe     PetscReal a[3] = {0., 0., 0.}, vel[3] = {0., 0., 0.};
12008214e71cSJoe 
12018214e71cSJoe     PetscCall(PetscRandomGetValueReal(rnd, &a[0]));
12028214e71cSJoe     if (user->perturbed_weights) {
12038214e71cSJoe       PetscCall(PetscPDFSampleConstant1D(a, NULL, vel));
12048214e71cSJoe     } else {
12058214e71cSJoe       PetscCall(PetscPDFSampleGaussian1D(a, NULL, vel));
12068214e71cSJoe     }
12078214e71cSJoe     v[p * dim] = vel[0];
12088214e71cSJoe   }
12098214e71cSJoe   PetscCall(PetscRandomDestroy(&rnd));
12108214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "velocity", NULL, NULL, (void **)&v));
12118214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "species", NULL, NULL, (void **)&species));
12128214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
12138214e71cSJoe }
12148214e71cSJoe 
12158214e71cSJoe static PetscErrorCode CreateSwarm(DM dm, AppCtx *user, DM *sw)
12168214e71cSJoe {
12178214e71cSJoe   PetscReal v0[2] = {1., 0.};
12188214e71cSJoe   PetscInt  dim;
1219b80bf5b1SJoe Pusztay 
1220b80bf5b1SJoe Pusztay   PetscFunctionBeginUser;
12219566063dSJacob Faibussowitsch   PetscCall(DMGetDimension(dm, &dim));
12229566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)dm), sw));
12239566063dSJacob Faibussowitsch   PetscCall(DMSetType(*sw, DMSWARM));
12249566063dSJacob Faibussowitsch   PetscCall(DMSetDimension(*sw, dim));
12259566063dSJacob Faibussowitsch   PetscCall(DMSwarmSetType(*sw, DMSWARM_PIC));
12269566063dSJacob Faibussowitsch   PetscCall(DMSwarmSetCellDM(*sw, dm));
12279566063dSJacob Faibussowitsch   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "w_q", 1, PETSC_SCALAR));
12288214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "velocity", dim, PETSC_REAL));
12298214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "species", 1, PETSC_INT));
12308214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "initCoordinates", dim, PETSC_REAL));
12318214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "initVelocity", dim, PETSC_REAL));
12328214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "E_field", dim, PETSC_REAL));
12338214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "potential", dim, PETSC_REAL));
12348214e71cSJoe   PetscCall(DMSwarmRegisterPetscDatatypeField(*sw, "charges", dim, PETSC_REAL));
12359566063dSJacob Faibussowitsch   PetscCall(DMSwarmFinalizeFieldRegister(*sw));
12368214e71cSJoe   PetscCall(DMSetApplicationContext(*sw, user));
12379566063dSJacob Faibussowitsch   PetscCall(DMSetFromOptions(*sw));
12388214e71cSJoe   user->swarm = *sw;
12398214e71cSJoe   if (user->perturbed_weights) {
12408214e71cSJoe     PetscCall(InitializeParticles_PerturbedWeights(*sw, user));
1241b80bf5b1SJoe Pusztay   } else {
12428214e71cSJoe     PetscCall(DMSwarmComputeLocalSizeFromOptions(*sw));
12438214e71cSJoe     PetscCall(DMSwarmInitializeCoordinates(*sw));
12448214e71cSJoe     if (user->fake_1D) {
12458214e71cSJoe       PetscCall(InitializeVelocities_Fake1D(*sw, user));
12469371c9d4SSatish Balay     } else {
12478214e71cSJoe       PetscCall(DMSwarmInitializeVelocitiesFromOptions(*sw, v0));
1248b80bf5b1SJoe Pusztay     }
1249b80bf5b1SJoe Pusztay   }
12509566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetName((PetscObject)*sw, "Particles"));
12519566063dSJacob Faibussowitsch   PetscCall(DMViewFromOptions(*sw, NULL, "-sw_view"));
12528214e71cSJoe   {
12538214e71cSJoe     Vec gc, gc0, gv, gv0;
12548214e71cSJoe 
12558214e71cSJoe     PetscCall(DMSwarmCreateGlobalVectorFromField(*sw, DMSwarmPICField_coor, &gc));
12568214e71cSJoe     PetscCall(DMSwarmCreateGlobalVectorFromField(*sw, "initCoordinates", &gc0));
12578214e71cSJoe     PetscCall(VecCopy(gc, gc0));
12588214e71cSJoe     PetscCall(VecViewFromOptions(gc, NULL, "-ic_x_view"));
12598214e71cSJoe     PetscCall(DMSwarmDestroyGlobalVectorFromField(*sw, DMSwarmPICField_coor, &gc));
12608214e71cSJoe     PetscCall(DMSwarmDestroyGlobalVectorFromField(*sw, "initCoordinates", &gc0));
12618214e71cSJoe     PetscCall(DMSwarmCreateGlobalVectorFromField(*sw, "velocity", &gv));
12628214e71cSJoe     PetscCall(DMSwarmCreateGlobalVectorFromField(*sw, "initVelocity", &gv0));
12638214e71cSJoe     PetscCall(VecCopy(gv, gv0));
12648214e71cSJoe     PetscCall(VecViewFromOptions(gv, NULL, "-ic_v_view"));
12658214e71cSJoe     PetscCall(DMSwarmDestroyGlobalVectorFromField(*sw, "velocity", &gv));
12668214e71cSJoe     PetscCall(DMSwarmDestroyGlobalVectorFromField(*sw, "initVelocity", &gv0));
12678214e71cSJoe   }
1268*84467f86SMatthew G. Knepley   {
1269*84467f86SMatthew G. Knepley     const char *fieldnames[2] = {DMSwarmPICField_coor, "velocity"};
1270*84467f86SMatthew G. Knepley 
1271*84467f86SMatthew G. Knepley     PetscCall(DMSwarmVectorDefineField(*sw, 2, fieldnames));
1272*84467f86SMatthew G. Knepley   }
12733ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1274b80bf5b1SJoe Pusztay }
1275b80bf5b1SJoe Pusztay 
12768214e71cSJoe static PetscErrorCode ComputeFieldAtParticles_Coulomb(SNES snes, DM sw, PetscReal E[])
1277d71ae5a4SJacob Faibussowitsch {
12788214e71cSJoe   AppCtx     *user;
12798214e71cSJoe   PetscReal  *coords;
12808214e71cSJoe   PetscInt   *species, dim, Np, Ns;
12818214e71cSJoe   PetscMPIInt size;
12828214e71cSJoe 
12838214e71cSJoe   PetscFunctionBegin;
12848214e71cSJoe   PetscCallMPI(MPI_Comm_size(PetscObjectComm((PetscObject)snes), &size));
12858214e71cSJoe   PetscCheck(size == 1, PetscObjectComm((PetscObject)snes), PETSC_ERR_SUP, "Coulomb code only works in serial");
12868214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
12878214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
12888214e71cSJoe   PetscCall(DMSwarmGetNumSpecies(sw, &Ns));
12898214e71cSJoe   PetscCall(DMGetApplicationContext(sw, (void *)&user));
12908214e71cSJoe 
12918214e71cSJoe   PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&coords));
12928214e71cSJoe   PetscCall(DMSwarmGetField(sw, "species", NULL, NULL, (void **)&species));
12938214e71cSJoe   for (PetscInt p = 0; p < Np; ++p) {
12948214e71cSJoe     PetscReal *pcoord = &coords[p * dim];
12958214e71cSJoe     PetscReal  pE[3]  = {0., 0., 0.};
12968214e71cSJoe 
12978214e71cSJoe     /* Calculate field at particle p due to particle q */
12988214e71cSJoe     for (PetscInt q = 0; q < Np; ++q) {
12998214e71cSJoe       PetscReal *qcoord = &coords[q * dim];
13008214e71cSJoe       PetscReal  rpq[3], r, r3, q_q;
13018214e71cSJoe 
13028214e71cSJoe       if (p == q) continue;
13038214e71cSJoe       q_q = user->charges[species[q]] * 1.;
13048214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) rpq[d] = pcoord[d] - qcoord[d];
13058214e71cSJoe       r = DMPlex_NormD_Internal(dim, rpq);
13068214e71cSJoe       if (r < PETSC_SQRT_MACHINE_EPSILON) continue;
13078214e71cSJoe       r3 = PetscPowRealInt(r, 3);
13088214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) pE[d] += q_q * rpq[d] / r3;
13098214e71cSJoe     }
13108214e71cSJoe     for (PetscInt d = 0; d < dim; ++d) E[p * dim + d] = pE[d];
13118214e71cSJoe   }
13128214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "species", NULL, NULL, (void **)&species));
13138214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&coords));
13148214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
13158214e71cSJoe }
13168214e71cSJoe 
13178214e71cSJoe static PetscErrorCode ComputeFieldAtParticles_Primal(SNES snes, DM sw, PetscReal E[])
13188214e71cSJoe {
1319b80bf5b1SJoe Pusztay   DM         dm;
13208214e71cSJoe   AppCtx    *user;
13218214e71cSJoe   PetscDS    ds;
13228214e71cSJoe   PetscFE    fe;
13238214e71cSJoe   Mat        M_p, M;
13248214e71cSJoe   Vec        phi, locPhi, rho, f;
13258214e71cSJoe   PetscReal *coords;
13268214e71cSJoe   PetscInt   dim, cStart, cEnd, Np;
13278214e71cSJoe 
13288214e71cSJoe   PetscFunctionBegin;
1329*84467f86SMatthew G. Knepley   PetscCall(DMGetApplicationContext(sw, (void *)&user));
1330*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventBegin(user->ESolveEvent, snes, sw, 0, 0));
13318214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
13328214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
13338214e71cSJoe 
13348214e71cSJoe   KSP          ksp;
13358214e71cSJoe   Vec          rho0;
1336*84467f86SMatthew G. Knepley   const char **oldFields;
1337*84467f86SMatthew G. Knepley   const char  *fields[1] = {"w_q"};
1338*84467f86SMatthew G. Knepley   PetscInt     Nf;
1339*84467f86SMatthew G. Knepley   const char **tmp;
13408214e71cSJoe 
13418214e71cSJoe   /* Create the charges rho */
13428214e71cSJoe   PetscCall(SNESGetDM(snes, &dm));
1343*84467f86SMatthew G. Knepley   PetscCall(DMSwarmVectorGetField(sw, &Nf, &tmp));
1344*84467f86SMatthew G. Knepley   PetscCall(PetscMalloc1(Nf, &oldFields));
1345*84467f86SMatthew G. Knepley   for (PetscInt f = 0; f < Nf; ++f) PetscCall(PetscStrallocpy(tmp[f], (char **)&oldFields[f]));
1346*84467f86SMatthew G. Knepley   PetscCall(DMSwarmVectorDefineField(sw, 1, fields));
13478214e71cSJoe   PetscCall(DMCreateMassMatrix(sw, dm, &M_p));
1348*84467f86SMatthew G. Knepley   PetscCall(DMSwarmVectorDefineField(sw, Nf, oldFields));
1349*84467f86SMatthew G. Knepley   for (PetscInt f = 0; f < Nf; ++f) PetscCall(PetscFree(oldFields[f]));
1350*84467f86SMatthew G. Knepley   PetscCall(PetscFree(oldFields));
13518214e71cSJoe 
13528214e71cSJoe   PetscCall(DMCreateMassMatrix(dm, dm, &M));
13538214e71cSJoe   PetscCall(DMGetGlobalVector(dm, &rho0));
13548214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)rho0, "Charge density (rho0) from Primal Compute"));
13558214e71cSJoe   PetscCall(DMGetGlobalVector(dm, &rho));
13568214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)rho, "rho"));
13578214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "w_q", &f));
13588214e71cSJoe 
13598214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)f, "particle weight"));
13608214e71cSJoe   PetscCall(MatMultTranspose(M_p, f, rho));
13618214e71cSJoe   PetscCall(MatViewFromOptions(M_p, NULL, "-mp_view"));
13628214e71cSJoe   PetscCall(MatViewFromOptions(M, NULL, "-m_view"));
13638214e71cSJoe   PetscCall(VecViewFromOptions(f, NULL, "-weights_view"));
13648214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "w_q", &f));
13658214e71cSJoe 
13668214e71cSJoe   PetscCall(KSPCreate(PetscObjectComm((PetscObject)dm), &ksp));
13678214e71cSJoe   PetscCall(KSPSetOptionsPrefix(ksp, "em_proj_"));
13688214e71cSJoe   PetscCall(KSPSetOperators(ksp, M, M));
13698214e71cSJoe   PetscCall(KSPSetFromOptions(ksp));
13708214e71cSJoe   PetscCall(KSPSolve(ksp, rho, rho0));
13718214e71cSJoe   PetscCall(VecViewFromOptions(rho0, NULL, "-rho0_view"));
13728214e71cSJoe 
13738214e71cSJoe   PetscInt           rhosize;
13748214e71cSJoe   PetscReal         *charges;
13758214e71cSJoe   const PetscScalar *rho_vals;
13768214e71cSJoe   PetscCall(DMSwarmGetField(sw, "charges", NULL, NULL, (void **)&charges));
13778214e71cSJoe   PetscCall(VecGetLocalSize(rho0, &rhosize));
13788214e71cSJoe   PetscCall(VecGetArrayRead(rho0, &rho_vals));
13798214e71cSJoe   for (PetscInt c = 0; c < rhosize; ++c) charges[c] = rho_vals[c];
13808214e71cSJoe   PetscCall(VecRestoreArrayRead(rho0, &rho_vals));
13818214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "charges", NULL, NULL, (void **)&charges));
13828214e71cSJoe 
13838214e71cSJoe   PetscCall(VecScale(rho, -1.0));
13848214e71cSJoe 
13858214e71cSJoe   PetscCall(VecViewFromOptions(rho0, NULL, "-rho0_view"));
13868214e71cSJoe   PetscCall(VecViewFromOptions(rho, NULL, "-rho_view"));
13878214e71cSJoe   PetscCall(DMRestoreGlobalVector(dm, &rho0));
13888214e71cSJoe   PetscCall(KSPDestroy(&ksp));
13898214e71cSJoe   PetscCall(MatDestroy(&M_p));
13908214e71cSJoe   PetscCall(MatDestroy(&M));
13918214e71cSJoe 
13928214e71cSJoe   PetscCall(DMGetGlobalVector(dm, &phi));
13938214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)phi, "potential"));
13948214e71cSJoe   PetscCall(VecSet(phi, 0.0));
13958214e71cSJoe   PetscCall(SNESSolve(snes, rho, phi));
13968214e71cSJoe   PetscCall(DMRestoreGlobalVector(dm, &rho));
13978214e71cSJoe   PetscCall(VecViewFromOptions(phi, NULL, "-phi_view"));
13988214e71cSJoe 
13998214e71cSJoe   PetscInt           phisize;
14008214e71cSJoe   PetscReal         *pot;
14018214e71cSJoe   const PetscScalar *phi_vals;
14028214e71cSJoe   PetscCall(DMSwarmGetField(sw, "potential", NULL, NULL, (void **)&pot));
14038214e71cSJoe   PetscCall(VecGetLocalSize(phi, &phisize));
14048214e71cSJoe   PetscCall(VecGetArrayRead(phi, &phi_vals));
14058214e71cSJoe   for (PetscInt c = 0; c < phisize; ++c) pot[c] = phi_vals[c];
14068214e71cSJoe   PetscCall(VecRestoreArrayRead(phi, &phi_vals));
14078214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "potential", NULL, NULL, (void **)&pot));
14088214e71cSJoe 
14098214e71cSJoe   PetscCall(DMGetLocalVector(dm, &locPhi));
14108214e71cSJoe   PetscCall(DMGlobalToLocalBegin(dm, phi, INSERT_VALUES, locPhi));
14118214e71cSJoe   PetscCall(DMGlobalToLocalEnd(dm, phi, INSERT_VALUES, locPhi));
14128214e71cSJoe   PetscCall(DMRestoreGlobalVector(dm, &phi));
1413*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventEnd(user->ESolveEvent, snes, sw, 0, 0));
14148214e71cSJoe 
14158214e71cSJoe   PetscCall(DMGetDS(dm, &ds));
14168214e71cSJoe   PetscCall(PetscDSGetDiscretization(ds, 0, (PetscObject *)&fe));
14178214e71cSJoe   PetscCall(DMSwarmSortGetAccess(sw));
14188214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
14198214e71cSJoe   PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&coords));
14208214e71cSJoe 
1421*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventBegin(user->ETabEvent, snes, sw, 0, 0));
14228214e71cSJoe   for (PetscInt c = cStart; c < cEnd; ++c) {
14238214e71cSJoe     PetscTabulation tab;
14248214e71cSJoe     PetscScalar    *clPhi = NULL;
14258214e71cSJoe     PetscReal      *pcoord, *refcoord;
14268214e71cSJoe     PetscReal       v[3], J[9], invJ[9], detJ;
14278214e71cSJoe     PetscInt       *points;
14288214e71cSJoe     PetscInt        Ncp;
14298214e71cSJoe 
14308214e71cSJoe     PetscCall(DMSwarmSortGetPointsPerCell(sw, c, &Ncp, &points));
14318214e71cSJoe     PetscCall(DMGetWorkArray(dm, Ncp * dim, MPIU_REAL, &pcoord));
14328214e71cSJoe     PetscCall(DMGetWorkArray(dm, Ncp * dim, MPIU_REAL, &refcoord));
14338214e71cSJoe     for (PetscInt cp = 0; cp < Ncp; ++cp)
14348214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) pcoord[cp * dim + d] = coords[points[cp] * dim + d];
1435*84467f86SMatthew G. Knepley     PetscCall(DMPlexCoordinatesToReference(dm, PETSC_TRUE, c, Ncp, pcoord, refcoord));
14368214e71cSJoe     PetscCall(PetscFECreateTabulation(fe, 1, Ncp, refcoord, 1, &tab));
14378214e71cSJoe     PetscCall(DMPlexComputeCellGeometryFEM(dm, c, NULL, v, J, invJ, &detJ));
14388214e71cSJoe     PetscCall(DMPlexVecGetClosure(dm, NULL, locPhi, c, NULL, &clPhi));
14398214e71cSJoe     for (PetscInt cp = 0; cp < Ncp; ++cp) {
14408214e71cSJoe       const PetscReal *basisDer = tab->T[1];
14418214e71cSJoe       const PetscInt   p        = points[cp];
14428214e71cSJoe 
14438214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) E[p * dim + d] = 0.;
14448214e71cSJoe       PetscCall(PetscFEFreeInterpolateGradient_Static(fe, basisDer, clPhi, dim, invJ, NULL, cp, &E[p * dim]));
14458214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) {
14468214e71cSJoe         E[p * dim + d] *= -1.0;
14478214e71cSJoe         if (user->fake_1D && d > 0) E[p * dim + d] = 0;
14488214e71cSJoe       }
14498214e71cSJoe     }
14508214e71cSJoe     PetscCall(DMPlexVecRestoreClosure(dm, NULL, locPhi, c, NULL, &clPhi));
14518214e71cSJoe     PetscCall(DMRestoreWorkArray(dm, Ncp * dim, MPIU_REAL, &pcoord));
14528214e71cSJoe     PetscCall(DMRestoreWorkArray(dm, Ncp * dim, MPIU_REAL, &refcoord));
14538214e71cSJoe     PetscCall(PetscTabulationDestroy(&tab));
1454*84467f86SMatthew G. Knepley     PetscCall(DMSwarmSortRestorePointsPerCell(sw, c, &Ncp, &points));
14558214e71cSJoe   }
14568214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&coords));
14578214e71cSJoe   PetscCall(DMSwarmSortRestoreAccess(sw));
14588214e71cSJoe   PetscCall(DMRestoreLocalVector(dm, &locPhi));
1459*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventEnd(user->ETabEvent, snes, sw, 0, 0));
14608214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
14618214e71cSJoe }
14628214e71cSJoe 
14638214e71cSJoe static PetscErrorCode ComputeFieldAtParticles_Mixed(SNES snes, DM sw, PetscReal E[])
14648214e71cSJoe {
14658214e71cSJoe   AppCtx         *user;
14668214e71cSJoe   DM              dm, potential_dm;
14678214e71cSJoe   KSP             ksp;
14688214e71cSJoe   IS              potential_IS;
14698214e71cSJoe   PetscDS         ds;
14708214e71cSJoe   PetscFE         fe;
14718214e71cSJoe   PetscFEGeom     feGeometry;
14728214e71cSJoe   Mat             M_p, M;
14738214e71cSJoe   Vec             phi, locPhi, rho, f, temp_rho, rho0;
14748214e71cSJoe   PetscQuadrature q;
14758214e71cSJoe   PetscReal      *coords, *pot;
1476*84467f86SMatthew G. Knepley   PetscInt        dim, cStart, cEnd, Np, pot_field = 1;
1477*84467f86SMatthew G. Knepley   const char    **oldFields;
1478*84467f86SMatthew G. Knepley   const char     *fields[1] = {"w_q"};
1479*84467f86SMatthew G. Knepley   PetscInt        Nf;
1480*84467f86SMatthew G. Knepley   const char    **tmp;
14818214e71cSJoe 
14828214e71cSJoe   PetscFunctionBegin;
1483*84467f86SMatthew G. Knepley   PetscCall(DMGetApplicationContext(sw, &user));
1484*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventBegin(user->ESolveEvent, snes, sw, 0, 0));
14858214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
14868214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
14878214e71cSJoe 
14888214e71cSJoe   /* Create the charges rho */
14898214e71cSJoe   PetscCall(SNESGetDM(snes, &dm));
14908214e71cSJoe   PetscCall(DMGetGlobalVector(dm, &rho));
14918214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)rho, "rho"));
14928214e71cSJoe 
1493*84467f86SMatthew G. Knepley   PetscCall(DMCreateSubDM(dm, 1, &pot_field, &potential_IS, &potential_dm));
14948214e71cSJoe 
1495*84467f86SMatthew G. Knepley   PetscCall(DMSwarmVectorGetField(sw, &Nf, &tmp));
1496*84467f86SMatthew G. Knepley   PetscCall(PetscMalloc1(Nf, &oldFields));
1497*84467f86SMatthew G. Knepley   for (PetscInt f = 0; f < Nf; ++f) PetscCall(PetscStrallocpy(tmp[f], (char **)&oldFields[f]));
1498*84467f86SMatthew G. Knepley   PetscCall(DMSwarmVectorDefineField(sw, 1, fields));
14998214e71cSJoe   PetscCall(DMCreateMassMatrix(sw, potential_dm, &M_p));
1500*84467f86SMatthew G. Knepley   PetscCall(DMSwarmVectorDefineField(sw, Nf, oldFields));
1501*84467f86SMatthew G. Knepley   for (PetscInt f = 0; f < Nf; ++f) PetscCall(PetscFree(oldFields[f]));
1502*84467f86SMatthew G. Knepley   PetscCall(PetscFree(oldFields));
15038214e71cSJoe 
15048214e71cSJoe   PetscCall(DMCreateMassMatrix(potential_dm, potential_dm, &M));
15058214e71cSJoe   PetscCall(MatViewFromOptions(M_p, NULL, "-mp_view"));
15068214e71cSJoe   PetscCall(MatViewFromOptions(M, NULL, "-m_view"));
15078214e71cSJoe   PetscCall(DMGetGlobalVector(potential_dm, &temp_rho));
15088214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)temp_rho, "Mf"));
15098214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "w_q", &f));
15108214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)f, "particle weight"));
15118214e71cSJoe   PetscCall(VecViewFromOptions(f, NULL, "-weights_view"));
15128214e71cSJoe   PetscCall(MatMultTranspose(M_p, f, temp_rho));
15138214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "w_q", &f));
15148214e71cSJoe   PetscCall(DMGetGlobalVector(potential_dm, &rho0));
15158214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)rho0, "Charge density (rho0) from Mixed Compute"));
15168214e71cSJoe 
15178214e71cSJoe   PetscCall(KSPCreate(PetscObjectComm((PetscObject)dm), &ksp));
15188214e71cSJoe   PetscCall(KSPSetOptionsPrefix(ksp, "em_proj"));
15198214e71cSJoe   PetscCall(KSPSetOperators(ksp, M, M));
15208214e71cSJoe   PetscCall(KSPSetFromOptions(ksp));
15218214e71cSJoe   PetscCall(KSPSolve(ksp, temp_rho, rho0));
15228214e71cSJoe   PetscCall(VecViewFromOptions(rho0, NULL, "-rho0_view"));
15238214e71cSJoe 
15248214e71cSJoe   PetscInt           rhosize;
15258214e71cSJoe   PetscReal         *charges;
15268214e71cSJoe   const PetscScalar *rho_vals;
15278214e71cSJoe   Parameter         *param;
15288214e71cSJoe   PetscCall(PetscBagGetData(user->bag, (void **)&param));
15298214e71cSJoe   PetscCall(DMSwarmGetField(sw, "charges", NULL, NULL, (void **)&charges));
15308214e71cSJoe   PetscCall(VecGetLocalSize(rho0, &rhosize));
15318214e71cSJoe 
15328214e71cSJoe   /* Integral over reference element is size 1.  Reference element area is 4.  Scale rho0 by 1/4 because the basis function is 1/4 */
15338214e71cSJoe   PetscCall(VecScale(rho0, 0.25));
15348214e71cSJoe   PetscCall(VecGetArrayRead(rho0, &rho_vals));
15358214e71cSJoe   for (PetscInt c = 0; c < rhosize; ++c) charges[c] = rho_vals[c];
15368214e71cSJoe   PetscCall(VecRestoreArrayRead(rho0, &rho_vals));
15378214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "charges", NULL, NULL, (void **)&charges));
15388214e71cSJoe 
15398214e71cSJoe   PetscCall(VecISCopy(rho, potential_IS, SCATTER_FORWARD, temp_rho));
15408214e71cSJoe   PetscCall(VecScale(rho, 0.25));
15418214e71cSJoe   PetscCall(VecViewFromOptions(rho0, NULL, "-rho0_view"));
15428214e71cSJoe   PetscCall(VecViewFromOptions(temp_rho, NULL, "-temprho_view"));
15438214e71cSJoe   PetscCall(VecViewFromOptions(rho, NULL, "-rho_view"));
15448214e71cSJoe   PetscCall(DMRestoreGlobalVector(potential_dm, &temp_rho));
15458214e71cSJoe   PetscCall(DMRestoreGlobalVector(potential_dm, &rho0));
15468214e71cSJoe 
15478214e71cSJoe   PetscCall(MatDestroy(&M_p));
15488214e71cSJoe   PetscCall(MatDestroy(&M));
15498214e71cSJoe   PetscCall(KSPDestroy(&ksp));
15508214e71cSJoe   PetscCall(DMDestroy(&potential_dm));
15518214e71cSJoe   PetscCall(ISDestroy(&potential_IS));
15528214e71cSJoe 
15538214e71cSJoe   PetscCall(DMGetGlobalVector(dm, &phi));
15548214e71cSJoe   PetscCall(PetscObjectSetName((PetscObject)phi, "potential"));
15558214e71cSJoe   PetscCall(VecSet(phi, 0.0));
15568214e71cSJoe   PetscCall(SNESSolve(snes, rho, phi));
15578214e71cSJoe   PetscCall(DMRestoreGlobalVector(dm, &rho));
15588214e71cSJoe 
15598214e71cSJoe   PetscInt           phisize;
15608214e71cSJoe   const PetscScalar *phi_vals;
15618214e71cSJoe   PetscCall(DMSwarmGetField(sw, "potential", NULL, NULL, (void **)&pot));
15628214e71cSJoe   PetscCall(VecGetLocalSize(phi, &phisize));
15638214e71cSJoe   PetscCall(VecViewFromOptions(phi, NULL, "-phi_view"));
15648214e71cSJoe   PetscCall(VecGetArrayRead(phi, &phi_vals));
15658214e71cSJoe   for (PetscInt c = 0; c < phisize; ++c) pot[c] = phi_vals[c];
15668214e71cSJoe   PetscCall(VecRestoreArrayRead(phi, &phi_vals));
15678214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "potential", NULL, NULL, (void **)&pot));
15688214e71cSJoe 
15698214e71cSJoe   PetscCall(DMGetLocalVector(dm, &locPhi));
15708214e71cSJoe   PetscCall(DMGlobalToLocalBegin(dm, phi, INSERT_VALUES, locPhi));
15718214e71cSJoe   PetscCall(DMGlobalToLocalEnd(dm, phi, INSERT_VALUES, locPhi));
15728214e71cSJoe   PetscCall(DMRestoreGlobalVector(dm, &phi));
1573*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventEnd(user->ESolveEvent, snes, sw, 0, 0));
15748214e71cSJoe 
1575*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventBegin(user->ETabEvent, snes, sw, 0, 0));
15768214e71cSJoe   PetscCall(DMGetDS(dm, &ds));
15778214e71cSJoe   PetscCall(PetscDSGetDiscretization(ds, 0, (PetscObject *)&fe));
15788214e71cSJoe   PetscCall(DMSwarmSortGetAccess(sw));
15798214e71cSJoe   PetscCall(DMPlexGetHeightStratum(dm, 0, &cStart, &cEnd));
15808214e71cSJoe   PetscCall(DMSwarmGetField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&coords));
15818214e71cSJoe   PetscCall(PetscFEGetQuadrature(fe, &q));
15828214e71cSJoe   PetscCall(PetscFECreateCellGeometry(fe, q, &feGeometry));
15838214e71cSJoe   for (PetscInt c = cStart; c < cEnd; ++c) {
15848214e71cSJoe     PetscTabulation tab;
15858214e71cSJoe     PetscScalar    *clPhi = NULL;
15868214e71cSJoe     PetscReal      *pcoord, *refcoord;
15878214e71cSJoe     PetscInt       *points;
15888214e71cSJoe     PetscInt        Ncp;
15898214e71cSJoe 
15908214e71cSJoe     PetscCall(DMSwarmSortGetPointsPerCell(sw, c, &Ncp, &points));
15918214e71cSJoe     PetscCall(DMGetWorkArray(dm, Ncp * dim, MPIU_REAL, &pcoord));
15928214e71cSJoe     PetscCall(DMGetWorkArray(dm, Ncp * dim, MPIU_REAL, &refcoord));
15938214e71cSJoe     for (PetscInt cp = 0; cp < Ncp; ++cp)
15948214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) pcoord[cp * dim + d] = coords[points[cp] * dim + d];
1595*84467f86SMatthew G. Knepley     PetscCall(DMPlexCoordinatesToReference(dm, PETSC_TRUE, c, Ncp, pcoord, refcoord));
15968214e71cSJoe     PetscCall(PetscFECreateTabulation(fe, 1, Ncp, refcoord, 1, &tab));
15978214e71cSJoe     PetscCall(DMPlexComputeCellGeometryFEM(dm, c, q, feGeometry.v, feGeometry.J, feGeometry.invJ, feGeometry.detJ));
15988214e71cSJoe     PetscCall(DMPlexVecGetClosure(dm, NULL, locPhi, c, NULL, &clPhi));
15998214e71cSJoe 
16008214e71cSJoe     for (PetscInt cp = 0; cp < Ncp; ++cp) {
16018214e71cSJoe       const PetscInt p = points[cp];
16028214e71cSJoe 
16038214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) E[p * dim + d] = 0.;
16048214e71cSJoe       PetscCall(PetscFEInterpolateAtPoints_Static(fe, tab, clPhi, &feGeometry, cp, &E[p * dim]));
16058214e71cSJoe       PetscCall(PetscFEPushforward(fe, &feGeometry, 1, &E[p * dim]));
16068214e71cSJoe       for (PetscInt d = 0; d < dim; ++d) {
16078214e71cSJoe         E[p * dim + d] *= -2.0;
16088214e71cSJoe         if (user->fake_1D && d > 0) E[p * dim + d] = 0;
16098214e71cSJoe       }
16108214e71cSJoe     }
16118214e71cSJoe     PetscCall(DMPlexVecRestoreClosure(dm, NULL, locPhi, c, NULL, &clPhi));
16128214e71cSJoe     PetscCall(DMRestoreWorkArray(dm, Ncp * dim, MPIU_REAL, &pcoord));
16138214e71cSJoe     PetscCall(DMRestoreWorkArray(dm, Ncp * dim, MPIU_REAL, &refcoord));
16148214e71cSJoe     PetscCall(PetscTabulationDestroy(&tab));
1615*84467f86SMatthew G. Knepley     PetscCall(DMSwarmSortRestorePointsPerCell(sw, c, &Ncp, &points));
16168214e71cSJoe   }
16178214e71cSJoe   PetscCall(PetscFEDestroyCellGeometry(fe, &feGeometry));
16188214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, DMSwarmPICField_coor, NULL, NULL, (void **)&coords));
16198214e71cSJoe   PetscCall(DMSwarmSortRestoreAccess(sw));
16208214e71cSJoe   PetscCall(DMRestoreLocalVector(dm, &locPhi));
1621*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventEnd(user->ETabEvent, snes, sw, 0, 0));
16228214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
16238214e71cSJoe }
16248214e71cSJoe 
16258214e71cSJoe static PetscErrorCode ComputeFieldAtParticles(SNES snes, DM sw, PetscReal E[])
16268214e71cSJoe {
16278214e71cSJoe   AppCtx  *ctx;
16288214e71cSJoe   PetscInt dim, Np;
16298214e71cSJoe 
16308214e71cSJoe   PetscFunctionBegin;
16318214e71cSJoe   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
16328214e71cSJoe   PetscValidHeaderSpecific(sw, DM_CLASSID, 2);
16338214e71cSJoe   PetscAssertPointer(E, 3);
16348214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
16358214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
16368214e71cSJoe   PetscCall(DMGetApplicationContext(sw, &ctx));
16378214e71cSJoe   PetscCall(PetscArrayzero(E, Np * dim));
16388214e71cSJoe 
16398214e71cSJoe   switch (ctx->em) {
16408214e71cSJoe   case EM_PRIMAL:
16418214e71cSJoe     PetscCall(ComputeFieldAtParticles_Primal(snes, sw, E));
16428214e71cSJoe     break;
16438214e71cSJoe   case EM_COULOMB:
16448214e71cSJoe     PetscCall(ComputeFieldAtParticles_Coulomb(snes, sw, E));
16458214e71cSJoe     break;
16468214e71cSJoe   case EM_MIXED:
16478214e71cSJoe     PetscCall(ComputeFieldAtParticles_Mixed(snes, sw, E));
16488214e71cSJoe     break;
16498214e71cSJoe   case EM_NONE:
16508214e71cSJoe     break;
16518214e71cSJoe   default:
16528214e71cSJoe     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No solver for electrostatic model %s", EMTypes[ctx->em]);
16538214e71cSJoe   }
16548214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
16558214e71cSJoe }
16568214e71cSJoe 
16578214e71cSJoe static PetscErrorCode RHSFunction(TS ts, PetscReal t, Vec U, Vec G, void *ctx)
16588214e71cSJoe {
16598214e71cSJoe   DM                 sw;
16608214e71cSJoe   SNES               snes = ((AppCtx *)ctx)->snes;
16618214e71cSJoe   const PetscReal   *coords, *vel;
16628214e71cSJoe   const PetscScalar *u;
16638214e71cSJoe   PetscScalar       *g;
16648214e71cSJoe   PetscReal         *E, m_p = 1., q_p = -1.;
16658214e71cSJoe   PetscInt           dim, d, Np, p;
1666b80bf5b1SJoe Pusztay 
1667b80bf5b1SJoe Pusztay   PetscFunctionBeginUser;
16688214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
16698214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
16708214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
16718214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initVelocity", NULL, NULL, (void **)&vel));
16728214e71cSJoe   PetscCall(DMSwarmGetField(sw, "E_field", NULL, NULL, (void **)&E));
16738214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
16748214e71cSJoe   PetscCall(VecGetArrayRead(U, &u));
16758214e71cSJoe   PetscCall(VecGetArray(G, &g));
16768214e71cSJoe 
16778214e71cSJoe   PetscCall(ComputeFieldAtParticles(snes, sw, E));
16788214e71cSJoe 
16798214e71cSJoe   Np /= 2 * dim;
16808214e71cSJoe   for (p = 0; p < Np; ++p) {
16818214e71cSJoe     for (d = 0; d < dim; ++d) {
16828214e71cSJoe       g[(p * 2 + 0) * dim + d] = u[(p * 2 + 1) * dim + d];
16838214e71cSJoe       g[(p * 2 + 1) * dim + d] = q_p * E[p * dim + d] / m_p;
16848214e71cSJoe     }
16858214e71cSJoe   }
16868214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
16878214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initVelocity", NULL, NULL, (void **)&vel));
16888214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "E_field", NULL, NULL, (void **)&E));
16898214e71cSJoe   PetscCall(VecRestoreArrayRead(U, &u));
16908214e71cSJoe   PetscCall(VecRestoreArray(G, &g));
16918214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
16928214e71cSJoe }
16938214e71cSJoe 
16948214e71cSJoe /* J_{ij} = dF_i/dx_j
16958214e71cSJoe    J_p = (  0   1)
16968214e71cSJoe          (-w^2  0)
16978214e71cSJoe    TODO Now there is another term with w^2 from the electric field. I think we will need to invert the operator.
16988214e71cSJoe         Perhaps we can approximate the Jacobian using only the cellwise P-P gradient from Coulomb
16998214e71cSJoe */
17008214e71cSJoe static PetscErrorCode RHSJacobian(TS ts, PetscReal t, Vec U, Mat J, Mat P, void *ctx)
17018214e71cSJoe {
17028214e71cSJoe   DM               sw;
17038214e71cSJoe   const PetscReal *coords, *vel;
17048214e71cSJoe   PetscInt         dim, d, Np, p, rStart;
17058214e71cSJoe 
17068214e71cSJoe   PetscFunctionBeginUser;
17078214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
17088214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
17098214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
17108214e71cSJoe   PetscCall(MatGetOwnershipRange(J, &rStart, NULL));
17118214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
17128214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initVelocity", NULL, NULL, (void **)&vel));
17138214e71cSJoe   Np /= 2 * dim;
17148214e71cSJoe   for (p = 0; p < Np; ++p) {
17158214e71cSJoe     const PetscReal x0      = coords[p * dim + 0];
17168214e71cSJoe     const PetscReal vy0     = vel[p * dim + 1];
17178214e71cSJoe     const PetscReal omega   = vy0 / x0;
17188214e71cSJoe     PetscScalar     vals[4] = {0., 1., -PetscSqr(omega), 0.};
17198214e71cSJoe 
17208214e71cSJoe     for (d = 0; d < dim; ++d) {
17218214e71cSJoe       const PetscInt rows[2] = {(p * 2 + 0) * dim + d + rStart, (p * 2 + 1) * dim + d + rStart};
17228214e71cSJoe       PetscCall(MatSetValues(J, 2, rows, 2, rows, vals, INSERT_VALUES));
17238214e71cSJoe     }
17248214e71cSJoe   }
17258214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
17268214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initVelocity", NULL, NULL, (void **)&vel));
17278214e71cSJoe   PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
17288214e71cSJoe   PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
17298214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
17308214e71cSJoe }
17318214e71cSJoe 
17328214e71cSJoe static PetscErrorCode RHSFunctionX(TS ts, PetscReal t, Vec V, Vec Xres, void *ctx)
17338214e71cSJoe {
17348214e71cSJoe   AppCtx            *user = (AppCtx *)ctx;
17358214e71cSJoe   DM                 sw;
17368214e71cSJoe   const PetscScalar *v;
17378214e71cSJoe   PetscScalar       *xres;
17388214e71cSJoe   PetscInt           Np, p, d, dim;
17398214e71cSJoe 
17408214e71cSJoe   PetscFunctionBeginUser;
1741*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventBegin(user->RhsXEvent, ts, 0, 0, 0));
17428214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
17438214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
17448214e71cSJoe   PetscCall(VecGetLocalSize(Xres, &Np));
17459566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(V, &v));
17468214e71cSJoe   PetscCall(VecGetArray(Xres, &xres));
1747b80bf5b1SJoe Pusztay   Np /= dim;
1748b80bf5b1SJoe Pusztay   for (p = 0; p < Np; ++p) {
17498214e71cSJoe     for (d = 0; d < dim; ++d) {
17508214e71cSJoe       xres[p * dim + d] = v[p * dim + d];
17518214e71cSJoe       if (user->fake_1D && d > 0) xres[p * dim + d] = 0;
17528214e71cSJoe     }
1753b80bf5b1SJoe Pusztay   }
17549566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(V, &v));
17558214e71cSJoe   PetscCall(VecRestoreArray(Xres, &xres));
1756*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventEnd(user->RhsXEvent, ts, 0, 0, 0));
17573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1758b80bf5b1SJoe Pusztay }
1759b80bf5b1SJoe Pusztay 
17608214e71cSJoe static PetscErrorCode RHSFunctionV(TS ts, PetscReal t, Vec X, Vec Vres, void *ctx)
17618214e71cSJoe {
17628214e71cSJoe   DM                 sw;
17638214e71cSJoe   AppCtx            *user = (AppCtx *)ctx;
17648214e71cSJoe   SNES               snes = ((AppCtx *)ctx)->snes;
17658214e71cSJoe   const PetscScalar *x;
17668214e71cSJoe   const PetscReal   *coords, *vel;
17678214e71cSJoe   PetscReal         *E, m_p, q_p;
17688214e71cSJoe   PetscScalar       *vres;
17698214e71cSJoe   PetscInt           Np, p, dim, d;
17708214e71cSJoe   Parameter         *param;
17718214e71cSJoe 
17728214e71cSJoe   PetscFunctionBeginUser;
1773*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventBegin(user->RhsVEvent, ts, 0, 0, 0));
17748214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
17758214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
17768214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
17778214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initVelocity", NULL, NULL, (void **)&vel));
17788214e71cSJoe   PetscCall(DMSwarmGetField(sw, "E_field", NULL, NULL, (void **)&E));
17798214e71cSJoe   PetscCall(PetscBagGetData(user->bag, (void **)&param));
17808214e71cSJoe   m_p = user->masses[0] * param->m0;
17818214e71cSJoe   q_p = user->charges[0] * param->q0;
17828214e71cSJoe   PetscCall(VecGetLocalSize(Vres, &Np));
17838214e71cSJoe   PetscCall(VecGetArrayRead(X, &x));
17848214e71cSJoe   PetscCall(VecGetArray(Vres, &vres));
17858214e71cSJoe   PetscCheck(dim == 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Dimension must be 2");
17868214e71cSJoe   PetscCall(ComputeFieldAtParticles(snes, sw, E));
17878214e71cSJoe 
17888214e71cSJoe   Np /= dim;
17898214e71cSJoe   for (p = 0; p < Np; ++p) {
17908214e71cSJoe     for (d = 0; d < dim; ++d) {
17918214e71cSJoe       vres[p * dim + d] = q_p * E[p * dim + d] / m_p;
17928214e71cSJoe       if (user->fake_1D && d > 0) vres[p * dim + d] = 0.;
17938214e71cSJoe     }
17948214e71cSJoe   }
17958214e71cSJoe   PetscCall(VecRestoreArrayRead(X, &x));
17968214e71cSJoe   /*
1797d7c1f440SPierre Jolivet     Synchronized, ordered output for parallel/sequential test cases.
17988214e71cSJoe     In the 1D (on the 2D mesh) case, every y component should be zero.
17998214e71cSJoe   */
18008214e71cSJoe   if (user->checkVRes) {
18018214e71cSJoe     PetscBool pr = user->checkVRes > 1 ? PETSC_TRUE : PETSC_FALSE;
18028214e71cSJoe     PetscInt  step;
18038214e71cSJoe 
18048214e71cSJoe     PetscCall(TSGetStepNumber(ts, &step));
18058214e71cSJoe     if (pr) PetscCall(PetscPrintf(PETSC_COMM_WORLD, "step: %" PetscInt_FMT "\n", step));
18068214e71cSJoe     for (PetscInt p = 0; p < Np; ++p) {
18078214e71cSJoe       if (pr) PetscCall(PetscSynchronizedPrintf(PETSC_COMM_WORLD, "Residual: %.12g %.12g\n", (double)PetscRealPart(vres[p * dim + 0]), (double)PetscRealPart(vres[p * dim + 1])));
18088214e71cSJoe       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]));
18098214e71cSJoe     }
18108214e71cSJoe     if (pr) PetscCall(PetscSynchronizedFlush(PETSC_COMM_WORLD, PETSC_STDOUT));
18118214e71cSJoe   }
18128214e71cSJoe   PetscCall(VecRestoreArray(Vres, &vres));
18138214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
18148214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initVelocity", NULL, NULL, (void **)&vel));
18158214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "E_field", NULL, NULL, (void **)&E));
1816*84467f86SMatthew G. Knepley   PetscCall(PetscLogEventEnd(user->RhsVEvent, ts, 0, 0, 0));
18178214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
18188214e71cSJoe }
18198214e71cSJoe 
18208214e71cSJoe static PetscErrorCode CreateSolution(TS ts)
18218214e71cSJoe {
18228214e71cSJoe   DM       sw;
18238214e71cSJoe   Vec      u;
18248214e71cSJoe   PetscInt dim, Np;
18258214e71cSJoe 
18268214e71cSJoe   PetscFunctionBegin;
18278214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
18288214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
18298214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
18308214e71cSJoe   PetscCall(VecCreate(PETSC_COMM_WORLD, &u));
18318214e71cSJoe   PetscCall(VecSetBlockSize(u, dim));
18328214e71cSJoe   PetscCall(VecSetSizes(u, 2 * Np * dim, PETSC_DECIDE));
18338214e71cSJoe   PetscCall(VecSetUp(u));
18348214e71cSJoe   PetscCall(TSSetSolution(ts, u));
18358214e71cSJoe   PetscCall(VecDestroy(&u));
18368214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
18378214e71cSJoe }
18388214e71cSJoe 
18398214e71cSJoe static PetscErrorCode SetProblem(TS ts)
18408214e71cSJoe {
18418214e71cSJoe   AppCtx *user;
18428214e71cSJoe   DM      sw;
18438214e71cSJoe 
18448214e71cSJoe   PetscFunctionBegin;
18458214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
18468214e71cSJoe   PetscCall(DMGetApplicationContext(sw, (void **)&user));
18478214e71cSJoe   // Define unified system for (X, V)
18488214e71cSJoe   {
18498214e71cSJoe     Mat      J;
18508214e71cSJoe     PetscInt dim, Np;
18518214e71cSJoe 
18528214e71cSJoe     PetscCall(DMGetDimension(sw, &dim));
18538214e71cSJoe     PetscCall(DMSwarmGetLocalSize(sw, &Np));
18548214e71cSJoe     PetscCall(MatCreate(PETSC_COMM_WORLD, &J));
18558214e71cSJoe     PetscCall(MatSetSizes(J, 2 * Np * dim, 2 * Np * dim, PETSC_DECIDE, PETSC_DECIDE));
18568214e71cSJoe     PetscCall(MatSetBlockSize(J, 2 * dim));
18578214e71cSJoe     PetscCall(MatSetFromOptions(J));
18588214e71cSJoe     PetscCall(MatSetUp(J));
18598214e71cSJoe     PetscCall(TSSetRHSFunction(ts, NULL, RHSFunction, user));
18608214e71cSJoe     PetscCall(TSSetRHSJacobian(ts, J, J, RHSJacobian, user));
18618214e71cSJoe     PetscCall(MatDestroy(&J));
18628214e71cSJoe   }
18638214e71cSJoe   /* Define split system for X and V */
18648214e71cSJoe   {
18658214e71cSJoe     Vec             u;
18668214e71cSJoe     IS              isx, isv, istmp;
18678214e71cSJoe     const PetscInt *idx;
18688214e71cSJoe     PetscInt        dim, Np, rstart;
18698214e71cSJoe 
18708214e71cSJoe     PetscCall(TSGetSolution(ts, &u));
18718214e71cSJoe     PetscCall(DMGetDimension(sw, &dim));
18728214e71cSJoe     PetscCall(DMSwarmGetLocalSize(sw, &Np));
18738214e71cSJoe     PetscCall(VecGetOwnershipRange(u, &rstart, NULL));
18748214e71cSJoe     PetscCall(ISCreateStride(PETSC_COMM_WORLD, Np, (rstart / dim) + 0, 2, &istmp));
18758214e71cSJoe     PetscCall(ISGetIndices(istmp, &idx));
18768214e71cSJoe     PetscCall(ISCreateBlock(PETSC_COMM_WORLD, dim, Np, idx, PETSC_COPY_VALUES, &isx));
18778214e71cSJoe     PetscCall(ISRestoreIndices(istmp, &idx));
18788214e71cSJoe     PetscCall(ISDestroy(&istmp));
18798214e71cSJoe     PetscCall(ISCreateStride(PETSC_COMM_WORLD, Np, (rstart / dim) + 1, 2, &istmp));
18808214e71cSJoe     PetscCall(ISGetIndices(istmp, &idx));
18818214e71cSJoe     PetscCall(ISCreateBlock(PETSC_COMM_WORLD, dim, Np, idx, PETSC_COPY_VALUES, &isv));
18828214e71cSJoe     PetscCall(ISRestoreIndices(istmp, &idx));
18838214e71cSJoe     PetscCall(ISDestroy(&istmp));
18848214e71cSJoe     PetscCall(TSRHSSplitSetIS(ts, "position", isx));
18858214e71cSJoe     PetscCall(TSRHSSplitSetIS(ts, "momentum", isv));
18868214e71cSJoe     PetscCall(ISDestroy(&isx));
18878214e71cSJoe     PetscCall(ISDestroy(&isv));
18888214e71cSJoe     PetscCall(TSRHSSplitSetRHSFunction(ts, "position", NULL, RHSFunctionX, user));
18898214e71cSJoe     PetscCall(TSRHSSplitSetRHSFunction(ts, "momentum", NULL, RHSFunctionV, user));
18908214e71cSJoe   }
18918214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
18928214e71cSJoe }
18938214e71cSJoe 
18948214e71cSJoe static PetscErrorCode DMSwarmTSRedistribute(TS ts)
18958214e71cSJoe {
18968214e71cSJoe   DM        sw;
18978214e71cSJoe   Vec       u;
18988214e71cSJoe   PetscReal t, maxt, dt;
18998214e71cSJoe   PetscInt  n, maxn;
19008214e71cSJoe 
19018214e71cSJoe   PetscFunctionBegin;
19028214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
19038214e71cSJoe   PetscCall(TSGetTime(ts, &t));
19048214e71cSJoe   PetscCall(TSGetMaxTime(ts, &maxt));
19058214e71cSJoe   PetscCall(TSGetTimeStep(ts, &dt));
19068214e71cSJoe   PetscCall(TSGetStepNumber(ts, &n));
19078214e71cSJoe   PetscCall(TSGetMaxSteps(ts, &maxn));
19088214e71cSJoe 
19098214e71cSJoe   PetscCall(TSReset(ts));
19108214e71cSJoe   PetscCall(TSSetDM(ts, sw));
19118214e71cSJoe   PetscCall(TSSetFromOptions(ts));
19128214e71cSJoe   PetscCall(TSSetTime(ts, t));
19138214e71cSJoe   PetscCall(TSSetMaxTime(ts, maxt));
19148214e71cSJoe   PetscCall(TSSetTimeStep(ts, dt));
19158214e71cSJoe   PetscCall(TSSetStepNumber(ts, n));
19168214e71cSJoe   PetscCall(TSSetMaxSteps(ts, maxn));
19178214e71cSJoe 
19188214e71cSJoe   PetscCall(CreateSolution(ts));
19198214e71cSJoe   PetscCall(SetProblem(ts));
19208214e71cSJoe   PetscCall(TSGetSolution(ts, &u));
19218214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
19228214e71cSJoe }
19238214e71cSJoe 
19248214e71cSJoe PetscErrorCode line(PetscInt dim, PetscReal time, const PetscReal dummy[], PetscInt p, PetscScalar x[], void *ctx)
19258214e71cSJoe {
19268214e71cSJoe   DM        sw, cdm;
19278214e71cSJoe   PetscInt  Np;
19288214e71cSJoe   PetscReal low[2], high[2];
19298214e71cSJoe   AppCtx   *user = (AppCtx *)ctx;
19308214e71cSJoe 
19318214e71cSJoe   sw = user->swarm;
19328214e71cSJoe   PetscCall(DMSwarmGetCellDM(sw, &cdm));
19338214e71cSJoe   // Get the bounding box so we can equally space the particles
19348214e71cSJoe   PetscCall(DMGetLocalBoundingBox(cdm, low, high));
19358214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
19368214e71cSJoe   // shift it by h/2 so nothing is initialized directly on a boundary
19378214e71cSJoe   x[0] = ((high[0] - low[0]) / Np) * (p + 0.5);
19388214e71cSJoe   x[1] = 0.;
19398214e71cSJoe   return PETSC_SUCCESS;
19408214e71cSJoe }
19418214e71cSJoe 
1942b80bf5b1SJoe Pusztay /*
19438214e71cSJoe   InitializeSolveAndSwarm - Set the solution values to the swarm coordinates and velocities, and also possibly set the initial values.
19448214e71cSJoe 
19458214e71cSJoe   Input Parameters:
19468214e71cSJoe + ts         - The TS
1947d7c1f440SPierre Jolivet - useInitial - Flag to also set the initial conditions to the current coordinates and velocities and setup the problem
19488214e71cSJoe 
19498214e71cSJoe   Output Parameters:
19508214e71cSJoe . u - The initialized solution vector
19518214e71cSJoe 
19528214e71cSJoe   Level: advanced
19538214e71cSJoe 
19548214e71cSJoe .seealso: InitializeSolve()
1955b80bf5b1SJoe Pusztay */
19568214e71cSJoe static PetscErrorCode InitializeSolveAndSwarm(TS ts, PetscBool useInitial)
1957d71ae5a4SJacob Faibussowitsch {
19588214e71cSJoe   DM       sw;
19598214e71cSJoe   Vec      u, gc, gv, gc0, gv0;
19608214e71cSJoe   IS       isx, isv;
19618214e71cSJoe   PetscInt dim;
19628214e71cSJoe   AppCtx  *user;
1963b80bf5b1SJoe Pusztay 
1964b80bf5b1SJoe Pusztay   PetscFunctionBeginUser;
19658214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
19668214e71cSJoe   PetscCall(DMGetApplicationContext(sw, &user));
19678214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
19688214e71cSJoe   if (useInitial) {
19698214e71cSJoe     PetscReal v0[2] = {1., 0.};
19708214e71cSJoe     if (user->perturbed_weights) {
19718214e71cSJoe       PetscCall(InitializeParticles_PerturbedWeights(sw, user));
19728214e71cSJoe     } else {
19738214e71cSJoe       PetscCall(DMSwarmComputeLocalSizeFromOptions(sw));
19748214e71cSJoe       PetscCall(DMSwarmInitializeCoordinates(sw));
19758214e71cSJoe       if (user->fake_1D) {
19768214e71cSJoe         PetscCall(InitializeVelocities_Fake1D(sw, user));
19778214e71cSJoe       } else {
19788214e71cSJoe         PetscCall(DMSwarmInitializeVelocitiesFromOptions(sw, v0));
19798214e71cSJoe       }
19808214e71cSJoe     }
19818214e71cSJoe     PetscCall(DMSwarmMigrate(sw, PETSC_TRUE));
19828214e71cSJoe     PetscCall(DMSwarmTSRedistribute(ts));
19838214e71cSJoe   }
19848214e71cSJoe   PetscCall(TSGetSolution(ts, &u));
19858214e71cSJoe   PetscCall(TSRHSSplitGetIS(ts, "position", &isx));
19868214e71cSJoe   PetscCall(TSRHSSplitGetIS(ts, "momentum", &isv));
19878214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, DMSwarmPICField_coor, &gc));
19888214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "initCoordinates", &gc0));
19898214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "velocity", &gv));
19908214e71cSJoe   PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "initVelocity", &gv0));
19918214e71cSJoe   if (useInitial) {
19928214e71cSJoe     PetscCall(VecCopy(gc, gc0));
19938214e71cSJoe     PetscCall(VecCopy(gv, gv0));
19948214e71cSJoe   }
19958214e71cSJoe   PetscCall(VecISCopy(u, isx, SCATTER_FORWARD, gc));
19968214e71cSJoe   PetscCall(VecISCopy(u, isv, SCATTER_FORWARD, gv));
19978214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, DMSwarmPICField_coor, &gc));
19988214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "initCoordinates", &gc0));
19998214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "velocity", &gv));
20008214e71cSJoe   PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "initVelocity", &gv0));
20018214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
20028214e71cSJoe }
20038214e71cSJoe 
20048214e71cSJoe static PetscErrorCode InitializeSolve(TS ts, Vec u)
2005b80bf5b1SJoe Pusztay {
20068214e71cSJoe   PetscFunctionBegin;
20078214e71cSJoe   PetscCall(TSSetSolution(ts, u));
20088214e71cSJoe   PetscCall(InitializeSolveAndSwarm(ts, PETSC_TRUE));
20098214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
2010b80bf5b1SJoe Pusztay }
2011b80bf5b1SJoe Pusztay 
20128214e71cSJoe static PetscErrorCode ComputeError(TS ts, Vec U, Vec E)
20138214e71cSJoe {
20148214e71cSJoe   MPI_Comm           comm;
20158214e71cSJoe   DM                 sw;
20168214e71cSJoe   AppCtx            *user;
20178214e71cSJoe   const PetscScalar *u;
20188214e71cSJoe   const PetscReal   *coords, *vel;
20198214e71cSJoe   PetscScalar       *e;
20208214e71cSJoe   PetscReal          t;
20218214e71cSJoe   PetscInt           dim, Np, p;
2022b80bf5b1SJoe Pusztay 
20238214e71cSJoe   PetscFunctionBeginUser;
20248214e71cSJoe   PetscCall(PetscObjectGetComm((PetscObject)ts, &comm));
20258214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
20268214e71cSJoe   PetscCall(DMGetApplicationContext(sw, &user));
20278214e71cSJoe   PetscCall(DMGetDimension(sw, &dim));
20288214e71cSJoe   PetscCall(TSGetSolveTime(ts, &t));
20298214e71cSJoe   PetscCall(VecGetArray(E, &e));
20308214e71cSJoe   PetscCall(VecGetArrayRead(U, &u));
20318214e71cSJoe   PetscCall(DMSwarmGetLocalSize(sw, &Np));
20328214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
20338214e71cSJoe   PetscCall(DMSwarmGetField(sw, "initVelocity", NULL, NULL, (void **)&vel));
20348214e71cSJoe   Np /= 2 * dim;
20358214e71cSJoe   for (p = 0; p < Np; ++p) {
20368214e71cSJoe     /* TODO generalize initial conditions and project into plane instead of assuming x-y */
20378214e71cSJoe     const PetscReal    r0    = DMPlex_NormD_Internal(dim, &coords[p * dim]);
20388214e71cSJoe     const PetscReal    th0   = PetscAtan2Real(coords[p * dim + 1], coords[p * dim + 0]);
20398214e71cSJoe     const PetscReal    v0    = DMPlex_NormD_Internal(dim, &vel[p * dim]);
20408214e71cSJoe     const PetscReal    omega = v0 / r0;
20418214e71cSJoe     const PetscReal    ct    = PetscCosReal(omega * t + th0);
20428214e71cSJoe     const PetscReal    st    = PetscSinReal(omega * t + th0);
20438214e71cSJoe     const PetscScalar *x     = &u[(p * 2 + 0) * dim];
20448214e71cSJoe     const PetscScalar *v     = &u[(p * 2 + 1) * dim];
20458214e71cSJoe     const PetscReal    xe[3] = {r0 * ct, r0 * st, 0.0};
20468214e71cSJoe     const PetscReal    ve[3] = {-v0 * st, v0 * ct, 0.0};
20478214e71cSJoe     PetscInt           d;
20488214e71cSJoe 
20498214e71cSJoe     for (d = 0; d < dim; ++d) {
20508214e71cSJoe       e[(p * 2 + 0) * dim + d] = x[d] - xe[d];
20518214e71cSJoe       e[(p * 2 + 1) * dim + d] = v[d] - ve[d];
2052b80bf5b1SJoe Pusztay     }
20538214e71cSJoe     if (user->error) {
20548214e71cSJoe       const PetscReal en   = 0.5 * DMPlex_DotRealD_Internal(dim, v, v);
20558214e71cSJoe       const PetscReal exen = 0.5 * PetscSqr(v0);
20568214e71cSJoe       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)));
2057b80bf5b1SJoe Pusztay     }
20588214e71cSJoe   }
20598214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initCoordinates", NULL, NULL, (void **)&coords));
20608214e71cSJoe   PetscCall(DMSwarmRestoreField(sw, "initVelocity", NULL, NULL, (void **)&vel));
20618214e71cSJoe   PetscCall(VecRestoreArrayRead(U, &u));
20628214e71cSJoe   PetscCall(VecRestoreArray(E, &e));
20638214e71cSJoe   PetscFunctionReturn(PETSC_SUCCESS);
20648214e71cSJoe }
20658214e71cSJoe 
20668214e71cSJoe static PetscErrorCode MigrateParticles(TS ts)
20678214e71cSJoe {
20688214e71cSJoe   DM               sw, cdm;
20698214e71cSJoe   const PetscReal *L;
20708214e71cSJoe 
20718214e71cSJoe   PetscFunctionBeginUser;
20728214e71cSJoe   PetscCall(TSGetDM(ts, &sw));
20738214e71cSJoe   PetscCall(DMViewFromOptions(sw, NULL, "-migrate_view_pre"));
20748214e71cSJoe   {
20758214e71cSJoe     Vec        u, gc, gv, position, momentum;
20768214e71cSJoe     IS         isx, isv;
20778214e71cSJoe     PetscReal *pos, *mom;
20788214e71cSJoe 
20798214e71cSJoe     PetscCall(TSGetSolution(ts, &u));
20808214e71cSJoe     PetscCall(TSRHSSplitGetIS(ts, "position", &isx));
20818214e71cSJoe     PetscCall(TSRHSSplitGetIS(ts, "momentum", &isv));
20828214e71cSJoe     PetscCall(VecGetSubVector(u, isx, &position));
20838214e71cSJoe     PetscCall(VecGetSubVector(u, isv, &momentum));
20848214e71cSJoe     PetscCall(VecGetArray(position, &pos));
20858214e71cSJoe     PetscCall(VecGetArray(momentum, &mom));
20868214e71cSJoe     PetscCall(DMSwarmCreateGlobalVectorFromField(sw, DMSwarmPICField_coor, &gc));
20878214e71cSJoe     PetscCall(DMSwarmCreateGlobalVectorFromField(sw, "velocity", &gv));
20888214e71cSJoe     PetscCall(VecISCopy(u, isx, SCATTER_REVERSE, gc));
20898214e71cSJoe     PetscCall(VecISCopy(u, isv, SCATTER_REVERSE, gv));
20908214e71cSJoe 
20918214e71cSJoe     PetscCall(DMSwarmGetCellDM(sw, &cdm));
20928214e71cSJoe     PetscCall(DMGetPeriodicity(cdm, NULL, NULL, &L));
20938214e71cSJoe     if ((L[0] || L[1]) >= 0.) {
20948214e71cSJoe       PetscReal *x, *v, upper[3], lower[3];
20958214e71cSJoe       PetscInt   Np, dim;
20968214e71cSJoe 
20978214e71cSJoe       PetscCall(DMSwarmGetLocalSize(sw, &Np));
20988214e71cSJoe       PetscCall(DMGetDimension(cdm, &dim));
20998214e71cSJoe       PetscCall(DMGetBoundingBox(cdm, lower, upper));
21008214e71cSJoe       PetscCall(VecGetArray(gc, &x));
21018214e71cSJoe       PetscCall(VecGetArray(gv, &v));
21028214e71cSJoe       for (PetscInt p = 0; p < Np; ++p) {
21038214e71cSJoe         for (PetscInt d = 0; d < dim; ++d) {
21048214e71cSJoe           if (pos[p * dim + d] < lower[d]) {
21058214e71cSJoe             x[p * dim + d] = pos[p * dim + d] + (upper[d] - lower[d]);
21068214e71cSJoe           } else if (pos[p * dim + d] > upper[d]) {
21078214e71cSJoe             x[p * dim + d] = pos[p * dim + d] - (upper[d] - lower[d]);
21088214e71cSJoe           } else {
21098214e71cSJoe             x[p * dim + d] = pos[p * dim + d];
21108214e71cSJoe           }
21118214e71cSJoe           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]);
21128214e71cSJoe           v[p * dim + d] = mom[p * dim + d];
21138214e71cSJoe         }
21148214e71cSJoe       }
21158214e71cSJoe       PetscCall(VecRestoreArray(gc, &x));
21168214e71cSJoe       PetscCall(VecRestoreArray(gv, &v));
21178214e71cSJoe     }
21188214e71cSJoe     PetscCall(VecRestoreArray(position, &pos));
21198214e71cSJoe     PetscCall(VecRestoreArray(momentum, &mom));
21208214e71cSJoe     PetscCall(VecRestoreSubVector(u, isx, &position));
21218214e71cSJoe     PetscCall(VecRestoreSubVector(u, isv, &momentum));
21228214e71cSJoe     PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, "velocity", &gv));
21238214e71cSJoe     PetscCall(DMSwarmDestroyGlobalVectorFromField(sw, DMSwarmPICField_coor, &gc));
21248214e71cSJoe   }
21258214e71cSJoe   PetscCall(DMSwarmMigrate(sw, PETSC_TRUE));
21268214e71cSJoe   PetscCall(DMSwarmTSRedistribute(ts));
21278214e71cSJoe   PetscCall(InitializeSolveAndSwarm(ts, PETSC_FALSE));
21283ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2129b80bf5b1SJoe Pusztay }
2130b80bf5b1SJoe Pusztay 
2131d71ae5a4SJacob Faibussowitsch int main(int argc, char **argv)
2132d71ae5a4SJacob Faibussowitsch {
2133b80bf5b1SJoe Pusztay   DM        dm, sw;
21348214e71cSJoe   TS        ts;
21358214e71cSJoe   Vec       u;
21368214e71cSJoe   PetscReal dt;
21378214e71cSJoe   PetscInt  maxn;
2138b80bf5b1SJoe Pusztay   AppCtx    user;
2139b80bf5b1SJoe Pusztay 
21409566063dSJacob Faibussowitsch   PetscCall(PetscInitialize(&argc, &argv, NULL, help));
21418214e71cSJoe   PetscCall(ProcessOptions(PETSC_COMM_WORLD, &user));
21428214e71cSJoe   PetscCall(PetscBagCreate(PETSC_COMM_SELF, sizeof(Parameter), &user.bag));
21438214e71cSJoe   PetscCall(CreateMesh(PETSC_COMM_WORLD, &user, &dm));
21448214e71cSJoe   PetscCall(CreatePoisson(dm, &user));
21458214e71cSJoe   PetscCall(CreateSwarm(dm, &user, &sw));
21468214e71cSJoe   PetscCall(SetupParameters(PETSC_COMM_WORLD, &user));
21478214e71cSJoe   PetscCall(InitializeConstants(sw, &user));
21488214e71cSJoe   PetscCall(DMSetApplicationContext(sw, &user));
2149b80bf5b1SJoe Pusztay 
21508214e71cSJoe   PetscCall(TSCreate(PETSC_COMM_WORLD, &ts));
21518214e71cSJoe   PetscCall(TSSetProblemType(ts, TS_NONLINEAR));
21529566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts, sw));
21538214e71cSJoe   PetscCall(TSSetMaxTime(ts, 0.1));
21548214e71cSJoe   PetscCall(TSSetTimeStep(ts, 0.00001));
21558214e71cSJoe   PetscCall(TSSetMaxSteps(ts, 100));
21568214e71cSJoe   PetscCall(TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP));
21578214e71cSJoe 
21588214e71cSJoe   if (user.efield_monitor) PetscCall(TSMonitorSet(ts, MonitorEField, &user, NULL));
21598214e71cSJoe   if (user.initial_monitor) PetscCall(TSMonitorSet(ts, MonitorInitialConditions, &user, NULL));
21608214e71cSJoe   if (user.monitor_positions) PetscCall(TSMonitorSet(ts, MonitorPositions_2D, &user, NULL));
21618214e71cSJoe   if (user.poisson_monitor) PetscCall(TSMonitorSet(ts, MonitorPoisson, &user, NULL));
21628214e71cSJoe 
21638214e71cSJoe   PetscCall(TSSetFromOptions(ts));
21648214e71cSJoe   PetscCall(TSGetTimeStep(ts, &dt));
21658214e71cSJoe   PetscCall(TSGetMaxSteps(ts, &maxn));
21668214e71cSJoe   user.steps    = maxn;
21678214e71cSJoe   user.stepSize = dt;
21688214e71cSJoe   PetscCall(SetupContext(dm, sw, &user));
21698214e71cSJoe   PetscCall(TSSetComputeInitialCondition(ts, InitializeSolve));
21708214e71cSJoe   PetscCall(TSSetComputeExactError(ts, ComputeError));
21718214e71cSJoe   PetscCall(TSSetPostStep(ts, MigrateParticles));
21728214e71cSJoe   PetscCall(CreateSolution(ts));
21738214e71cSJoe   PetscCall(TSGetSolution(ts, &u));
21748214e71cSJoe   PetscCall(TSComputeInitialCondition(ts, u));
21758214e71cSJoe   PetscCall(CheckNonNegativeWeights(sw, &user));
21768214e71cSJoe   PetscCall(TSSolve(ts, NULL));
21778214e71cSJoe 
21789566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&user.snes));
21799566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&ts));
21809566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&sw));
21819566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&dm));
21828214e71cSJoe   PetscCall(DestroyContext(&user));
21839566063dSJacob Faibussowitsch   PetscCall(PetscFinalize());
2184b122ec5aSJacob Faibussowitsch   return 0;
2185b80bf5b1SJoe Pusztay }
2186b80bf5b1SJoe Pusztay 
2187b80bf5b1SJoe Pusztay /*TEST
2188b80bf5b1SJoe Pusztay 
2189b80bf5b1SJoe Pusztay    build:
21908214e71cSJoe     requires: !complex double
21918214e71cSJoe 
21928214e71cSJoe   # This tests that we can put particles in a box and compute the Coulomb force
21938214e71cSJoe   # Recommend -draw_size 500,500
21948214e71cSJoe    testset:
21958214e71cSJoe      requires: defined(PETSC_HAVE_EXECUTABLE_EXPORT)
21968214e71cSJoe      args: -dm_plex_dim 2 -fake_1D -dm_plex_simplex 0 -dm_plex_box_faces 20,1 \
21978214e71cSJoe              -dm_plex_box_lower 0,-1 -dm_plex_box_upper 12.5664,1 \
2198b80bf5b1SJoe Pusztay              -dm_plex_box_bd periodic,none \
21998214e71cSJoe            -dm_swarm_coordinate_density constant -dm_swarm_num_particles 100 \
22008214e71cSJoe            -sigma 1.0e-8 -timeScale 2.0e-14 \
22018214e71cSJoe            -ts_type basicsymplectic -ts_basicsymplectic_type 1 \
22028214e71cSJoe              -ts_monitor_sp_swarm -ts_monitor_sp_swarm_retain 0 -ts_monitor_sp_swarm_phase 0 \
22038214e71cSJoe            -output_step 50 -check_vel_res
22048214e71cSJoe      test:
22058214e71cSJoe        suffix: none_1d
22068214e71cSJoe        args: -em_type none -error
22078214e71cSJoe      test:
22088214e71cSJoe        suffix: coulomb_1d
22098214e71cSJoe        args: -em_type coulomb
22108214e71cSJoe 
22118214e71cSJoe    # for viewers
22128214e71cSJoe    #-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
22138214e71cSJoe    testset:
22148214e71cSJoe      nsize: {{1 2}}
22158214e71cSJoe      requires: defined(PETSC_HAVE_EXECUTABLE_EXPORT)
22168214e71cSJoe      args: -dm_plex_dim 2 -fake_1D -dm_plex_simplex 0 -dm_plex_box_faces 36,1 \
22178214e71cSJoe              -dm_plex_box_lower 0.,-0.5 -dm_plex_box_upper 12.5664,0.5 \
22188214e71cSJoe              -dm_plex_box_bd periodic,none \
22198214e71cSJoe            -vdm_plex_dim 1 -vdm_plex_simplex 0 -vdm_plex_box_faces 10 \
22208214e71cSJoe              -vdm_plex_box_lower -3 -vdm_plex_box_upper 3 \
2221*84467f86SMatthew G. Knepley            -dm_swarm_num_species 1 -twostream -charges -1.,1. -sigma 1.0e-8 \
22228214e71cSJoe              -cosine_coefficients 0.01,0.5 -perturbed_weights -total_weight 1. \
22238214e71cSJoe            -ts_type basicsymplectic -ts_basicsymplectic_type 2 \
22248214e71cSJoe              -ts_dt 0.01 -ts_max_time 5 -ts_max_steps 10 \
22258214e71cSJoe            -em_snes_atol 1.e-15 -em_snes_error_if_not_converged -em_ksp_error_if_not_converged \
2226*84467f86SMatthew G. Knepley            -output_step 1 -check_vel_res -dm_swarm_print_coords 1 -dm_swarm_print_weights 1
22278214e71cSJoe      test:
22288214e71cSJoe        suffix: two_stream_c0
22298214e71cSJoe        args: -em_type primal -petscfe_default_quadrature_order 2 -petscspace_degree 2 -em_pc_type svd
22308214e71cSJoe      test:
22318214e71cSJoe        suffix: two_stream_rt
22328214e71cSJoe        requires: superlu_dist
22338214e71cSJoe        args: -em_type mixed \
22348214e71cSJoe                -potential_petscspace_degree 0 \
22358214e71cSJoe                -potential_petscdualspace_lagrange_use_moments \
22368214e71cSJoe                -potential_petscdualspace_lagrange_moment_order 2 \
22378214e71cSJoe                -field_petscspace_degree 2 -field_petscfe_default_quadrature_order 1 \
22388214e71cSJoe                -field_petscspace_type sum \
22398214e71cSJoe                  -field_petscspace_variables 2 \
22408214e71cSJoe                  -field_petscspace_components 2 \
22418214e71cSJoe                  -field_petscspace_sum_spaces 2 \
22428214e71cSJoe                  -field_petscspace_sum_concatenate true \
22438214e71cSJoe                  -field_sumcomp_0_petscspace_variables 2 \
22448214e71cSJoe                  -field_sumcomp_0_petscspace_type tensor \
22458214e71cSJoe                  -field_sumcomp_0_petscspace_tensor_spaces 2 \
22468214e71cSJoe                  -field_sumcomp_0_petscspace_tensor_uniform false \
22478214e71cSJoe                  -field_sumcomp_0_tensorcomp_0_petscspace_degree 1 \
22488214e71cSJoe                  -field_sumcomp_0_tensorcomp_1_petscspace_degree 0 \
22498214e71cSJoe                  -field_sumcomp_1_petscspace_variables 2 \
22508214e71cSJoe                  -field_sumcomp_1_petscspace_type tensor \
22518214e71cSJoe                  -field_sumcomp_1_petscspace_tensor_spaces 2 \
22528214e71cSJoe                  -field_sumcomp_1_petscspace_tensor_uniform false \
22538214e71cSJoe                  -field_sumcomp_1_tensorcomp_0_petscspace_degree 0 \
22548214e71cSJoe                  -field_sumcomp_1_tensorcomp_1_petscspace_degree 1 \
22558214e71cSJoe                -field_petscdualspace_form_degree -1 \
22568214e71cSJoe                -field_petscdualspace_order 1 \
22578214e71cSJoe                -field_petscdualspace_lagrange_trimmed true \
22588214e71cSJoe              -em_snes_error_if_not_converged \
22598214e71cSJoe              -em_ksp_type preonly -em_ksp_error_if_not_converged \
22608214e71cSJoe              -em_pc_type fieldsplit -em_pc_fieldsplit_type schur \
22618214e71cSJoe                -em_pc_fieldsplit_schur_fact_type full -em_pc_fieldsplit_schur_precondition full \
22628214e71cSJoe                -em_fieldsplit_field_pc_type lu \
22638214e71cSJoe                  -em_fieldsplit_field_pc_factor_mat_solver_type superlu_dist \
22648214e71cSJoe                -em_fieldsplit_potential_pc_type svd
22658214e71cSJoe 
2266*84467f86SMatthew G. Knepley    # For an eyeball check, we use
2267*84467f86SMatthew G. Knepley    # -ts_max_steps 1000 -dm_plex_box_faces 10,1 -vdm_plex_box_faces 2000 -monitor_efield
22688214e71cSJoe    # For verification, we use
2269*84467f86SMatthew G. Knepley    # -ts_max_steps 1000 -dm_plex_box_faces 100,1 -vdm_plex_box_faces 8000 -dm_swarm_num_particles 800000 -monitor_efield
22708214e71cSJoe    # -ts_monitor_sp_swarm_multi_species 0 -ts_monitor_sp_swarm_retain 0 -ts_monitor_sp_swarm_phase 1 -draw_size 500,500
22718214e71cSJoe    testset:
22728214e71cSJoe      nsize: {{1 2}}
22738214e71cSJoe      requires: defined(PETSC_HAVE_EXECUTABLE_EXPORT)
22748214e71cSJoe      args: -dm_plex_dim 2 -fake_1D -dm_plex_simplex 0 -dm_plex_box_faces 10,1 \
22758214e71cSJoe              -dm_plex_box_lower 0.,-0.5 -dm_plex_box_upper 12.5664,0.5 \
22768214e71cSJoe              -dm_plex_box_bd periodic,none \
22778214e71cSJoe            -vdm_plex_dim 1 -vdm_plex_simplex 0 -vdm_plex_box_faces 10 \
22788214e71cSJoe              -vdm_plex_box_lower -10 -vdm_plex_box_upper 10 \
2279*84467f86SMatthew G. Knepley            -dm_swarm_num_species 1 -charges -1.,1. \
22808214e71cSJoe              -cosine_coefficients 0.01,0.5 -perturbed_weights -total_weight 1. \
22818214e71cSJoe            -ts_type basicsymplectic -ts_basicsymplectic_type 1 \
22828214e71cSJoe              -ts_dt 0.03 -ts_max_time 500 -ts_max_steps 1 \
22838214e71cSJoe            -em_snes_atol 1.e-12 -em_snes_error_if_not_converged -em_ksp_error_if_not_converged \
2284*84467f86SMatthew G. Knepley            -output_step 1 -check_vel_res -dm_swarm_print_coords 1 -dm_swarm_print_weights 1
22858214e71cSJoe 
22868214e71cSJoe      test:
22878214e71cSJoe        suffix: uniform_equilibrium_1d
22888214e71cSJoe        args: -cosine_coefficients 0.0,0.5 -em_type primal -petscspace_degree 1 -em_pc_type svd
22898214e71cSJoe      test:
22908214e71cSJoe        suffix: uniform_primal_1d
22918214e71cSJoe        args: -em_type primal -petscspace_degree 1 -em_pc_type svd
22928214e71cSJoe      test:
22938214e71cSJoe        requires: superlu_dist
22948214e71cSJoe        suffix: uniform_mixed_1d
22958214e71cSJoe        args: -em_type mixed \
22968214e71cSJoe                -potential_petscspace_degree 0 \
22978214e71cSJoe                -potential_petscdualspace_lagrange_use_moments \
22988214e71cSJoe                -potential_petscdualspace_lagrange_moment_order 2 \
22998214e71cSJoe                -field_petscspace_degree 2 -field_petscfe_default_quadrature_order 1 \
23008214e71cSJoe                -field_petscspace_type sum \
23018214e71cSJoe                  -field_petscspace_variables 2 \
23028214e71cSJoe                  -field_petscspace_components 2 \
23038214e71cSJoe                  -field_petscspace_sum_spaces 2 \
23048214e71cSJoe                  -field_petscspace_sum_concatenate true \
23058214e71cSJoe                  -field_sumcomp_0_petscspace_variables 2 \
23068214e71cSJoe                  -field_sumcomp_0_petscspace_type tensor \
23078214e71cSJoe                  -field_sumcomp_0_petscspace_tensor_spaces 2 \
23088214e71cSJoe                  -field_sumcomp_0_petscspace_tensor_uniform false \
23098214e71cSJoe                  -field_sumcomp_0_tensorcomp_0_petscspace_degree 1 \
23108214e71cSJoe                  -field_sumcomp_0_tensorcomp_1_petscspace_degree 0 \
23118214e71cSJoe                  -field_sumcomp_1_petscspace_variables 2 \
23128214e71cSJoe                  -field_sumcomp_1_petscspace_type tensor \
23138214e71cSJoe                  -field_sumcomp_1_petscspace_tensor_spaces 2 \
23148214e71cSJoe                  -field_sumcomp_1_petscspace_tensor_uniform false \
23158214e71cSJoe                  -field_sumcomp_1_tensorcomp_0_petscspace_degree 0 \
23168214e71cSJoe                  -field_sumcomp_1_tensorcomp_1_petscspace_degree 1 \
23178214e71cSJoe                -field_petscdualspace_form_degree -1 \
23188214e71cSJoe                -field_petscdualspace_order 1 \
23198214e71cSJoe                -field_petscdualspace_lagrange_trimmed true \
23208214e71cSJoe              -em_snes_error_if_not_converged \
23218214e71cSJoe              -em_ksp_type preonly -em_ksp_error_if_not_converged \
23228214e71cSJoe              -em_pc_type fieldsplit -em_pc_fieldsplit_type schur \
23238214e71cSJoe                -em_pc_fieldsplit_schur_fact_type full -em_pc_fieldsplit_schur_precondition full \
23248214e71cSJoe                -em_fieldsplit_field_pc_type lu \
23258214e71cSJoe                  -em_fieldsplit_field_pc_factor_mat_solver_type superlu_dist \
23268214e71cSJoe                -em_fieldsplit_potential_pc_type svd
23278214e71cSJoe 
2328b80bf5b1SJoe Pusztay TEST*/
2329