XGC1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
species.hpp
Go to the documentation of this file.
1 #ifndef SPECIES_HPP
2 #define SPECIES_HPP
3 #include <Cabana_AoSoA.hpp>
4 #include <Cabana_DeepCopy.hpp>
5 #include <Kokkos_Core.hpp>
6 #include "NamelistReader.hpp"
7 #include "timer_macro.hpp"
8 #include "magnetic_field.hpp"
9 #include "grid.hpp"
10 #include "domain_decomposition.hpp"
11 #include "particles.hpp"
12 #include "space_settings.hpp"
13 #include "distribution.hpp"
14 #include "profile.hpp"
15 #include "gyro_avg_mat.hpp"
17 #include "basic_physics.hpp"
18 #include "memory_prediction.hpp"
19 #include "xgc_io.hpp"
20 
21 extern "C" void set_spall_num_and_ptr(int idx, int n_ptl, int n_vecs, VecParticles* ptl);
22 extern "C" void set_min_max_num(int isp, int n_ptl);
23 extern "C" void adjust_n_ptl_for_core_ptl(int* n_ptl);
24 
29  return false;
30 }
31 
36  return false;
37 }
38 
39 // Used for Cabana slices (getting one particle property at a time)
40 namespace PtlSlice{
41 #ifdef ESC_PTL
42 enum{Ph=0,Ct,Gid,Flag};
43 #else
44 enum{Ph=0,Ct,Gid};
45 #endif
46 }
47 
48 struct PtlMvmt{
49  // Options for particle location management when looping over particles
50  enum SendOpt{
51  NoSend=0,
54  };
55 
56  enum ReturnOpt{
60  };
61 
64 
65  PtlMvmt(SendOpt send_opt, ReturnOpt return_opt) : send_opt(send_opt), return_opt(return_opt){}
66 };
67 
71 };
72 
73 // Species class
74 template<class Device>
75 class Species{
76  public:
77 
78  int idx;
79  bool is_electron;
80  bool is_adiabatic;
83  double mass;
84  double charge;
85  double charge_eu;
86  double c_m;
87  double c2_2m;
88 
89  bool is_deltaf;
90 
91  int ncycles;
93 
95  int n_ptl;
96  Cabana::AoSoA<ParticleDataTypes,HostType,VEC_LEN> particles;
97 
98  // Device particles
99  Cabana::AoSoA<ParticleDataTypes,Device,VEC_LEN> particles_d;
100 
102 
105 
106  /*** Could be its own class inside species? ***/
110 
111  // phase0 (for ion restoration)
112  Cabana::AoSoA<PhaseDataTypes,HostType,VEC_LEN> phase0;
113  Cabana::AoSoA<PhaseDataTypes,Device,VEC_LEN> phase0_d;
114 
115  // For electron restoration
116  Cabana::AoSoA<ParticleDataTypes,HostType,VEC_LEN> backup_particles;
117  int n_backup_particles; // Number of particles stored in backup_particles (can't be deduced from its size due to buffer)
118  /****/
119 
121 
123 
124  Eq::Profile<Device> eq_temp; // Equilibrium temperature
125  Eq::Profile<Device> eq_den; // Equilibrium density
126  Eq::Profile<Device> eq_flow; // Equilibrium flow
127  int eq_flow_type; // Type of Equilibirum flow
128 
130 
131  /*** Constructors ***/
132 
133  Species(int idx_in, int nonadiabatic_idx_in, bool is_electron_in, bool is_adiabatic_in, KinType kintype_in, double mass_in, double charge_in, double charge_eu_in, bool is_deltaf_in,
134  int ncycles_in);
135 
136  Species(NLReader::NamelistReader& nlr, const Grid<DeviceType> &grid, const MagneticField<DeviceType> &magnetic_field, const DomainDecomposition<DeviceType>& pol_decomp, int idx_in, int nonadiabatic_idx_in);
137 
138  // Electron or ion default constructor
139  Species(SpeciesType sp_type, int n_ptl)
140  : idx(sp_type==ELECTRON ? 0 : 1),
141  is_electron(sp_type==ELECTRON),
142  mass(is_electron ? 3.344e-30 : PROTON_MASS),
144  charge_eu(is_electron ? -1.0 : 1.0),
145  is_deltaf(true),
146  is_adiabatic(false),
147  nonadiabatic_idx(idx), // Since is_adiabatic is false above
149  ncycles(is_electron ? 70 : 1),
150  c_m(charge/mass),
151  c2_2m(0.5*charge*charge/mass),
153  n_ptl(n_ptl),
154  backup_particles("backup_particles", 0),
155  particles("particles", add_vec_buffer(n_ptl)),
158  eq_temp(1.0e3,-0.1),
159  eq_den(1.0e19,-0.1),
160  eq_flow_type(2),
161  owns_particles_d(false),
165 
166  // Special constructor for tests that involve tracking particles in memory
167  // The idea is to use these particles to test functions that reorder particles,
168  // e.g. sort, shift, and cleaning
169  Species(int n_ptl_in)
170  : n_ptl(n_ptl_in),
171  is_electron(true),
172  is_adiabatic(false),
173  particles("particles", add_vec_buffer(n_ptl_in)),
175  owns_particles_d(false),
180  {
181 
182  // Slice particle properties
183  auto ph = Cabana::slice<PtlSlice::Ph>(particles);
184  auto ct = Cabana::slice<PtlSlice::Ct>(particles);
185  auto gid = Cabana::slice<PtlSlice::Gid>(particles);
186 #ifdef ESC_PTL
187  auto flag = Cabana::slice<PtlSlice::Flag>(particles);
188 #endif
189 
190  // Offset gid if using MPI
191 #ifdef USE_MPI
192  long long int gid_offset = n_ptl*SML_COMM_RANK;
193 #else
194  long long int gid_offset = 0;
195 #endif
196 
197  // Assign trackable values
198  for (int i=0;i<n_ptl;i++){
199  // Set GID in order
200  gid(i) = gid_offset + i+1; // 1-indexed
201 
202  // Value of properties is gid + 0.1*(property index)
203  // First particle: (1.0, 1.1, ... 1.8)
204  // Second particle: (2.0, 2.1, ... 2.8)
205  for (int j=0;j<6;j++) ph(i, j) = gid(i) + (j)*0.1;
206  for (int j=0;j<3;j++) ct(i, j) = gid(i) + (j+6)*0.1;
207  }
208 
209  // Buffer particles: same but with gid = -1
210  if(n_ptl>0){
211  for (int i=n_ptl;i<add_vec_buffer(n_ptl);i++){
212  gid(i) = -1;
213  for (int j=0;j<6;j++) ph(i, j) = gid(i) + (j)*0.1;
214  for (int j=0;j<3;j++) ct(i, j) = gid(i) + (j+6)*0.1;
215  }
216  }
217  }
218 
219  static std::vector<MemoryPrediction> estimate_memory_usage(NLReader::NamelistReader& nlr, const Grid<DeviceType> &grid, const DomainDecomposition<DeviceType>& pol_decomp, int species_idx);
220 
221  static int get_initial_n_ptl(NLReader::NamelistReader& nlr, const Grid<DeviceType> &grid, const DomainDecomposition<DeviceType>& pol_decomp, int sml_special, int species_idx, bool verbose);
222 
223  void resize_particles(int new_n_ptl){
224  n_ptl = new_n_ptl;
225 
226 #ifndef USE_GPU
227  // If CPU-only, particles_d points to the same location as particles. If particles is resized, then Cabana will not deallocate the first allocation
228  // since it is still used by particles_d. So, reset particles_d before resize, and point it back to particles only afterwards
229  particles_d = Cabana::AoSoA<ParticleDataTypes,Device,VEC_LEN>();
230 #endif
231 
232  particles.reserve(minimum_ptl_reservation); // Can only raise reservation (no-op if AoSoA is already larger)
233  particles.resize(add_vec_buffer(n_ptl));
234 
235 #ifndef USE_GPU
236  // Point particles_d back to particles after resize
238 #endif
239 
241  }
242 
244 #ifdef USE_GPU
245  particles.reserve(minimum_ptl_reservation); // Can only raise reservation (no-op if AoSoA is already larger)
246  particles.resize(particles_d.size());
247 #else
248  // Point particles back to particles_d after resize
250 #endif
251 
253  }
254 
255  /* If using CPU-only, then "device" particles are a shallow copy of host particles so that
256  * there is no unnecessary duplication. When "device" particles are resized, Cabana will keep the
257  * original allocation if there is a second reference (i.e. host particles).
258  * To resolve this, we free the host particles here so that there is no second reference
259  * */
261  particles = Cabana::AoSoA<ParticleDataTypes,HostType,VEC_LEN>();
262  }
263 
264  /* Resizes device particles if on GPU, or just creates a shallow copy if CPU only
265  * */
267  if(!owns_particles_d) exit_XGC("\nSpecies tried to resize device particles, but doesn't own the device array.");
268 
269 #ifdef USE_GPU
270  particles_d.reserve(minimum_ptl_reservation); // Can only raise reservation (no-op if AoSoA is already larger)
271  // Resize device particles to match n particles
273 #else
274  // If kernels are on CPU, do shallow copy
276 #endif
277  }
278 
279  /* Resizes device particles
280  * */
281  void resize_device_particles(int new_n_ptl){
282  if(!owns_particles_d) exit_XGC("\nSpecies tried to resize device particles, but doesn't own the device array.");
283 
284  n_ptl = new_n_ptl;
285 
286  particles_d.reserve(minimum_ptl_reservation); // Can only raise reservation (no-op if AoSoA is already larger)
287 
288  // Resize device particles to match host particles
290  }
291 
292  /* Copies particles to device - deep copy if using GPU, otherwise shallow copy
293  * Also takes the opportunity to set the buffer particles to realistic values
294  * */
296  if(!owns_particles_d) exit_XGC("\nSpecies tried to copy particles to device, but doesn't own the device array.");
297 
298 #ifdef USE_GPU
299  // Copy to device
300  Cabana::deep_copy(particles_d, particles);
301 #else
302  // No operation required if CPU-only
303 #endif
304 
305  // Copy last particle to fill remainder of trailing vector in AoSoA
307  }
308 
309  /* Copies particles from device - deep copy if using GPU, otherwise no copy is necessary
310  * */
312  if(!owns_particles_d) exit_XGC("\nSpecies tried to copy particles from device, but doesn't own the device array.");
313 
314 #ifdef USE_GPU
315  // Copy particles to host
316  Cabana::deep_copy(particles, particles_d);
317 #else
318  // No operation required if CPU-only
319 #endif
320  }
321 
322  /* Copies particles to device if they are resident on the device
323  * */
326  }
327 
328  /* Copies particles from device if they are resident on the device
329  * */
332  }
333 
334  /* Copies particles to device if they are NOT resident on the device
335  * */
338  }
339 
340  /* Copies particles from device if they are NOT resident on the device
341  * */
344  }
345 
354  if (n_ptl>0){
355  int last_ptl_index = n_ptl - 1;
356  auto ph = Cabana::slice<PtlSlice::Ph>(particles_d);
357  auto ct = Cabana::slice<PtlSlice::Ct>(particles_d);
358  auto gid = Cabana::slice<PtlSlice::Gid>(particles_d);
359 #ifdef ESC_PTL
360  auto flag = Cabana::slice<PtlSlice::Flag>(particles_d);
361 #endif
362 
363  Kokkos::parallel_for("set_buffer_particles_d", Kokkos::RangePolicy<ExSpace>( n_ptl, add_vec_buffer(n_ptl) ), KOKKOS_LAMBDA( const int i ){
364  // Buffer particles: same as last particle, gid = -1
365  for (int j=0;j<6;j++) ph(i, j) = ph(last_ptl_index, j);
366  for (int j=0;j<3;j++) ct(i, j) = ct(last_ptl_index, j);
367  gid(i) = -1;
368 #ifdef ESC_PTL
369  flag(i) = flag(last_ptl_index);
370 #endif
371  });
372  }
373  }
374 
383  if (n_ptl>0){
384  int last_ptl_index = n_ptl - 1;
385  auto ph = Cabana::slice<PtlSlice::Ph>(phase0_d);
386 
387  Kokkos::parallel_for("set_buffer_phase0", Kokkos::RangePolicy<ExSpace>( n_ptl, add_vec_buffer(n_ptl) ), KOKKOS_LAMBDA( const int i ){
388  // copy final real particle
389  for (int j=0;j<6;j++) ph(i, j) = ph(last_ptl_index, j);
390  });
391  }
392  }
393 
394  // Options for custom launch bounds since kokkos defaults are suboptimal for electron push kernel
395  enum class LaunchBounds{
396  Default,
397  Custom
398  };
399 
405  template<typename F>
406  inline void for_all_particles(const std::string label, F lambda_func) const {
407  Kokkos::RangePolicy<ExSpace> particle_range_policy( 0, p_range<DeviceType>(n_ptl) );
408  Kokkos::parallel_for(label, Opt::require(particle_range_policy, Async), lambda_func);
409  }
410 
411  inline void back_up_SoA(Cabana::AoSoA<ParticleDataTypes,Device,VEC_LEN>& backup_SoA, int offset, int n) const{
412  auto ph_b = Cabana::slice<PtlSlice::Ph>(backup_SoA);
413  auto ct_b = Cabana::slice<PtlSlice::Ct>(backup_SoA);
414  auto gid_b = Cabana::slice<PtlSlice::Gid>(backup_SoA);
415 #ifdef ESC_PTL
416  auto flag_b = Cabana::slice<PtlSlice::Flag>(backup_SoA);
417 #endif
418 
419  auto ph = Cabana::slice<PtlSlice::Ph>(particles_d);
420  auto ct = Cabana::slice<PtlSlice::Ct>(particles_d);
421  auto gid = Cabana::slice<PtlSlice::Gid>(particles_d);
422 #ifdef ESC_PTL
423  auto flag = Cabana::slice<PtlSlice::Flag>(particles_d);
424 #endif
425 
426  Kokkos::parallel_for("backup_first_soa", Kokkos::RangePolicy<ExSpace>( 0, n ), KOKKOS_LAMBDA( const int i ){
427  int i_offset = i + offset;
428  // Make backup copy
429  for (int j=0;j<6;j++) ph_b(i, j) = ph(i_offset, j);
430  for (int j=0;j<3;j++) ct_b(i, j) = ct(i_offset, j);
431  gid_b(i) = gid(i_offset);
432 #ifdef ESC_PTL
433  flag_b(i) = flag(i_offset);
434 #endif
435  // Deactivate
436  gid(i_offset) = -1;
437  });
438  }
439 
440  inline void restore_backup_SoA(Cabana::AoSoA<ParticleDataTypes,Device,VEC_LEN>& backup_SoA, int offset, int n) const{
441  auto ph_b = Cabana::slice<PtlSlice::Ph>(backup_SoA);
442  auto ct_b = Cabana::slice<PtlSlice::Ct>(backup_SoA);
443  auto gid_b = Cabana::slice<PtlSlice::Gid>(backup_SoA);
444 #ifdef ESC_PTL
445  auto flag_b = Cabana::slice<PtlSlice::Flag>(backup_SoA);
446 #endif
447 
448  auto ph = Cabana::slice<PtlSlice::Ph>(particles_d);
449  auto ct = Cabana::slice<PtlSlice::Ct>(particles_d);
450  auto gid = Cabana::slice<PtlSlice::Gid>(particles_d);
451 #ifdef ESC_PTL
452  auto flag = Cabana::slice<PtlSlice::Flag>(particles_d);
453 #endif
454 
455  Kokkos::parallel_for("backup_first_soa", Kokkos::RangePolicy<ExSpace>( 0, n ), KOKKOS_LAMBDA( const int i ){
456  int i_offset = i + offset;
457  // Restore from backup copy
458  for (int j=0;j<6;j++) ph(i_offset, j) = ph_b(i, j);
459  for (int j=0;j<3;j++) ct(i_offset, j) = ct_b(i, j);
460  gid(i_offset) = gid_b(i);
461 #ifdef ESC_PTL
462  flag(i_offset) = flag_b(i);
463 #endif
464  });
465  }
466 
472  template<typename F>
473  inline void for_particle_range(int begin_idx, int end_idx, const std::string label, F lambda_func) const {
474  if(end_idx <= begin_idx) return; // Return if range is 0 or less
475 
476  // Still need the subset to line up with the AoSoA vector length
477  int first_soa = begin_idx/VEC_LEN;
478  int n_other_ptl_in_first_soa = begin_idx - first_soa*VEC_LEN;
479  bool first_soa_is_partial = (n_other_ptl_in_first_soa>0);
480  int last_soa = (end_idx-1)/VEC_LEN;
481  int n_other_ptl_in_last_soa = (last_soa+1)*VEC_LEN - end_idx;
482  bool last_soa_is_partial = (n_other_ptl_in_last_soa>0);
483 
484 #ifdef USE_GPU
485  int first_item_in_shifted_range = first_soa*VEC_LEN;
486 #else
487  int first_item_in_shifted_range = first_soa;
488 #endif
489 
490  Cabana::AoSoA<ParticleDataTypes,Device,VEC_LEN> ptl_first_soa;
491  Cabana::AoSoA<ParticleDataTypes,Device,VEC_LEN> ptl_last_soa;
492  if(first_soa_is_partial){
493  // Make a backup of the first SoA and set the particles_d GIDs to -1
494  ptl_first_soa = Cabana::AoSoA<ParticleDataTypes,Device,VEC_LEN>("ptl_first_soa", n_other_ptl_in_first_soa);
495  back_up_SoA(ptl_first_soa, first_soa*VEC_LEN, n_other_ptl_in_first_soa);
496  }
497  if(last_soa_is_partial){
498  // Make a backup of the last SoA and set the particles_d GIDs to -1
499  ptl_last_soa = Cabana::AoSoA<ParticleDataTypes,Device,VEC_LEN>("ptl_last_soa", n_other_ptl_in_last_soa);
500  back_up_SoA(ptl_last_soa, end_idx, n_other_ptl_in_last_soa);
501  }
502 
503  // Finally, do the parallel_for
504  Kokkos::RangePolicy<ExSpace> particle_range_policy( first_item_in_shifted_range, p_range<DeviceType>(end_idx) );
505  Kokkos::parallel_for(label, Opt::require(particle_range_policy, Async), lambda_func);
506 
507  // Restore from backup
508  if(first_soa_is_partial){
509  restore_backup_SoA(ptl_first_soa, first_soa*VEC_LEN, n_other_ptl_in_first_soa);
510  }
511  if(last_soa_is_partial){
512  restore_backup_SoA(ptl_last_soa, end_idx, n_other_ptl_in_last_soa);
513  }
514  }
515 
523  template<typename F>
524  inline void for_all_particles(const std::string label, F lambda_func,
525  const PtlMvmt mvmt, LaunchBounds launch_bounds=LaunchBounds::Default) {
526  if(!owns_particles_d) exit_XGC("\nSpecies tried to loop over particles on device, but doesn't own the device array.");
527 
528  bool use_streaming = stream_particles;
529 #ifndef USE_STREAMS
530  use_streaming = false; // Just to be safe, turn streams off here
531 #endif
532 
533  bool send_ptl = ( mvmt.send_opt==PtlMvmt::Send ||
535  bool return_ptl = ( mvmt.return_opt==PtlMvmt::Return ||
537 
538  // Don't need to stream if particles are already present and don't need to be returned
539  if((!send_ptl) && (!return_ptl)) use_streaming = false;
540 
541  if(use_streaming){
542 #ifdef USE_STREAMS
543  Streamed::Option stream_option = Streamed::Normal; // Send to device and back
544  if(!send_ptl) stream_option = Streamed::NoSend;
545  if(!return_ptl) stream_option = Streamed::NoReturn;
546 
547  // Execute streaming parallel_for
548  Streamed::parallel_for(label, n_ptl, lambda_func, stream_option, particles, particles_d);
549 #endif
550  }else{
551  if(send_ptl) TIMER("copy_ptl_to_device",copy_particles_to_device() );
552 
553  if (launch_bounds==LaunchBounds::Custom) {
554 #ifdef USE_EPUSH_LAUNCH_BOUNDS
555 # if !defined(PUSH_MAX_THREADS_PER_BLOCK) || !defined(PUSH_MIN_WARPS_PER_EU)
556 # error "USE_EPUSH_LAUNCH_BOUNDS requires PUSH_MAX_THREADS_PER_BLOCK and PUSH_MIN_WARPS_PER_EU to be defined"
557 # endif
558  Kokkos::RangePolicy<ExSpace, Kokkos::LaunchBounds<PUSH_MAX_THREADS_PER_BLOCK, PUSH_MIN_WARPS_PER_EU>>
559  particle_range_policy( 0, p_range<DeviceType>(n_ptl) );
560  Kokkos::parallel_for(label, Opt::require(particle_range_policy, Async), lambda_func);
561 #else
562  exit_XGC("\nERROR: LaunchBounds::Custom specified, but USE_EPUSH_LAUNCH_BOUNDS is not defined\n");
563 #endif
564  } else {
565  Kokkos::RangePolicy<ExSpace>
566  particle_range_policy( 0, p_range<DeviceType>(n_ptl) );
567  Kokkos::parallel_for(label, Opt::require(particle_range_policy, Async), lambda_func);
568  }
569 
570  if(return_ptl) TIMER("copy_ptl_from_device", copy_particles_from_device() );
571  }
572  }
573 
574  KOKKOS_INLINE_FUNCTION VecParticles* ptl() const{
575  return (VecParticles*)(&particles_d.access(0));
576  }
577 
578  KOKKOS_INLINE_FUNCTION VecPhase* ph0() const{
579  return (VecPhase*)(&phase0_d.access(0));
580  }
581 
583  for_all_particles("copy_to_phase0", KOKKOS_LAMBDA( const int idx ){
584  AoSoAIndices<DeviceType> inds(idx);
585  VecParticles* ptl_loc = species.ptl();
586  VecPhase* ph0_loc = species.ph0();
587  for (int i_simd = 0; i_simd<SIMD_SIZE; i_simd++){
588  int p_vec = inds.a + i_simd;
589  ph0_loc[inds.s].r[p_vec] = ptl_loc[inds.s].ph.r[p_vec];
590  ph0_loc[inds.s].z[p_vec] = ptl_loc[inds.s].ph.z[p_vec];
591  ph0_loc[inds.s].phi[p_vec] = ptl_loc[inds.s].ph.phi[p_vec];
592  ph0_loc[inds.s].rho[p_vec] = ptl_loc[inds.s].ph.rho[p_vec];
593  ph0_loc[inds.s].w1[p_vec] = ptl_loc[inds.s].ph.w1[p_vec];
594  ph0_loc[inds.s].w2[p_vec] = ptl_loc[inds.s].ph.w2[p_vec];
595  }
596  });
597  }
598 
601  // If particles are resident on the device, then use the host particle allocation as the backup
602  // Otherwise, resize the backup_particle array
605  }else{
606  backup_particles.resize(particles_d.size());
607  }
608 
609  // Copy particle data to backup
610  Cabana::deep_copy(backup_particles, particles_d);
612  } else {
613  // For ions, save phase to phase0
614  phase0_d.resize(particles_d.size());
615  copy_to_phase0(*this); // Separate function to avoid implicit copy into lambda
616  }
618  }
619 
622  // If particles are resident on device, don't need to resize host particles since they are already used as the backup.
623  // If not, resize host particle array to fit backup particles
627  }else{
628  // If particles are not resident on device, resize host particle array to fit backup particles
630  }
631 
632  // Resize device particle array to fit backed up particles
634 
635  // Restore particle data from backup
636  Cabana::deep_copy(particles_d, backup_particles);
637 
639  // If the backup particles are simply pointing to the host particles, then
640  // point them to their own 0-sized allocation when finished using them
641  // so that they don't make a copy when host particles get resized
642  backup_particles = Cabana::AoSoA<ParticleDataTypes,HostType,VEC_LEN>("backup_particles", 0);
643  }
644  } else {
645  // When ipc==2, copy phase0 to device
646  // First, resize device phase0 and reset pointer
647  phase0_d.resize(phase0.size());
648 
649  // Next copy data to phase0 on device
650  Cabana::deep_copy(phase0_d, phase0);
651 
652  // Fill buffer with realistic ptl data
654  }
655  particles_are_backed_up = false;
656  }
657 
658  KOKKOS_INLINE_FUNCTION void restore_phase_from_phase0(const AoSoAIndices<Device>& inds, SimdParticles& part_one) const {
659  VecPhase* ph0_loc = ph0();
660  for (int i_simd = 0; i_simd<SIMD_SIZE; i_simd++){
661  int p_vec = inds.a + i_simd;
662  part_one.ph.r[i_simd] = ph0_loc[inds.s].r[p_vec];
663  part_one.ph.z[i_simd] = ph0_loc[inds.s].z[p_vec];
664  part_one.ph.phi[i_simd] = ph0_loc[inds.s].phi[p_vec];
665  part_one.ph.rho[i_simd] = ph0_loc[inds.s].rho[p_vec];
666  part_one.ph.w1[i_simd] = ph0_loc[inds.s].w1[p_vec];
667  part_one.ph.w2[i_simd] = ph0_loc[inds.s].w2[p_vec];
668  }
669  }
670 
671  long long int get_total_n_ptl(){
672 #ifdef USE_MPI
673  long long int tmp_n_ptl = n_ptl;
674  long long int out_n_ptl = 0;
675  MPI_Allreduce(&tmp_n_ptl, &out_n_ptl, 1, MPI_LONG_LONG_INT, MPI_SUM, SML_COMM_WORLD);
676  return out_n_ptl;
677 #else
678  return (long long int)(n_ptl);
679 #endif
680  }
681 
683 #ifdef USE_MPI
684  int tmp_n_ptl = n_ptl;
685  int out_n_ptl = 0;
686  MPI_Allreduce(&tmp_n_ptl, &out_n_ptl, 1, MPI_INT, MPI_MAX, SML_COMM_WORLD);
687  return out_n_ptl;
688 #else
689  return n_ptl;
690 #endif
691  }
692 
693  // Gets the gyro_radius of a species based on equilibrium temperature
694  // inode is the LOCAL (poloidally decomposed) grid node index to get temperature
695  // smu_n is the normalized sqrt(mu)
696  // bfield is the magnetic field at inode
697  KOKKOS_INLINE_FUNCTION double get_f0_eq_gyro_radius(int inode, double smu_n, double bfield) const{
698  // Should replace UNIT_CHARGE*charge_eu with charge(?)
699  return smu_n*sqrt(mass*f0.temp_ev(inode)*EV_2_J) / (UNIT_CHARGE*charge_eu*bfield);
700  }
701 
702  // Gets the equilibrium thermal velocity of a species based on f0 temperature
703  // inode is the GLOBAL node index to get temperature
704  KOKKOS_INLINE_FUNCTION double get_f0_eq_thermal_velocity(int inode) const{
705  return thermal_velocity(mass, f0.temp_global(inode));
706  }
707 
708  // Gets the equilibrium thermal velocity of a species based on f0 temperature, on device
709  // inode is the local node index to get temperature
710  KOKKOS_INLINE_FUNCTION double get_f0_eq_thermal_velocity_lnode(int inode) const{
711  return thermal_velocity(mass, f0.temp_ev(inode));
712  }
713 
714  // Gets the equilibrium thermal velocity of a species based on f0 temperature, on host
715  // inode is the local node index to get temperature
716  KOKKOS_INLINE_FUNCTION double get_f0_eq_thermal_velocity_lnode_h(int inode) const{
717  return thermal_velocity(mass, f0.temp_ev_h(inode));
718  }
719 
720  // Get species velocity
721  KOKKOS_INLINE_FUNCTION void get_particle_velocity_and_nearest_node(const Grid<DeviceType>& grid, const MagneticField<DeviceType>& magnetic_field, const DomainDecomposition<DeviceType>& pol_decomp, SimdParticles& part, Simd<double>& smu, Simd<double>& vp, Simd<int>& nearest_node, Simd<bool>& not_in_triangle, Simd<bool>& not_in_poloidal_domain) const{
722 
723  // This modulo surely doesnt need to be here (at least, should be elsewhere).
724  // Modulo phi coordinate
725  grid.wedge_modulo_phi(part.ph.phi);
726 
728  grid.get_grid_weights(magnetic_field, part.ph.v(), grid_wts0);
729 
730  // Output argument
731  for (int i_simd = 0; i_simd<SIMD_SIZE; i_simd++){
732  not_in_triangle[i_simd] = !grid_wts0.is_valid(i_simd);
733  }
734 
735  Simd<double> bmag;
736  magnetic_field.bmag_interpol(part.ph.v(), bmag);
737 
738  for (int i_simd = 0; i_simd<SIMD_SIZE; i_simd++){
739  if(!grid_wts0.is_valid(i_simd)) continue;
740 
741  nearest_node[i_simd]=grid_wts0.node[i_simd] - pol_decomp.node_offset;
742  not_in_poloidal_domain[i_simd] = (nearest_node[i_simd]<0 || nearest_node[i_simd]>=pol_decomp.nnodes);
743 
744  double temp_ev_norm = not_in_poloidal_domain[i_simd] ? f0.temp_ev(0) : f0.temp_ev(nearest_node[i_simd]);
745 
746  // get vp and smu
747  const double& B = bmag[i_simd];
748  vp[i_simd] = normalized_v_para(c_m, mass, B, temp_ev_norm, part.ph.rho[i_simd]);
749  smu[i_simd] = normalized_sqrt_mu(B, temp_ev_norm, part.ct.mu[i_simd]);
750  }
751  }
752 
754  const Grid<DeviceType>& grid,
756  const VelocityGrid& vgrid);
757 
760 
761  void write_ptl_checkpoint_files(const DomainDecomposition<DeviceType>& pol_decomp, const XGC_IO_Stream& stream, std::string sp_name);
762  void write_f0_checkpoint_files(const DomainDecomposition<DeviceType>& pol_decomp, const XGC_IO_Stream& stream, std::string sp_name);
763  void read_f0_checkpoint_files(const DomainDecomposition<DeviceType>& pol_decomp, const XGC_IO_Stream& stream, std::string sp_name);
764  void read_ptl_checkpoint_files(const DomainDecomposition<DeviceType>& pol_decomp, const XGC_IO_Stream& stream, std::string sp_name, bool n_ranks_is_same);
765 
766  long long int get_max_gid() const;
767  void get_ptl_write_total_and_offsets(const DomainDecomposition<DeviceType>& pol_decomp, long long int& inum_total, long long int& ioff) const;
768 };
769 
770 #endif
void calculate_global_f0_arrays(const Grid< DeviceType > &grid, const MagneticField< DeviceType > &magnetic_field)
Definition: species.cpp:432
Cabana::AoSoA< PhaseDataTypes, HostType, VEC_LEN > phase0
Definition: species.hpp:112
bool stream_particles
Whether to stream particles between host and device if possible.
Definition: species.hpp:104
Definition: globals.hpp:84
KOKKOS_INLINE_FUNCTION VecPhase * ph0() const
Definition: species.hpp:578
KOKKOS_INLINE_FUNCTION int divide_and_round_up(int a, int b)
Definition: globals.hpp:179
bool owns_particles_d
Whether the species owns the device particle allocation right now.
Definition: species.hpp:101
void back_up_SoA(Cabana::AoSoA< ParticleDataTypes, Device, VEC_LEN > &backup_SoA, int offset, int n) const
Definition: species.hpp:411
KOKKOS_INLINE_FUNCTION double normalized_v_para(double c_m, double mass, double B, double temp_ev, double rho)
Definition: basic_physics.hpp:80
KOKKOS_INLINE_FUNCTION double get_f0_eq_gyro_radius(int inode, double smu_n, double bfield) const
Definition: species.hpp:697
subroutine adjust_n_ptl_for_core_ptl(n_ptl)
Definition: load.F90:473
void set_spall_num_and_ptr(int idx, int n_ptl, int n_vecs, VecParticles *ptl)
void for_particle_range(int begin_idx, int end_idx, const std::string label, F lambda_func) const
Definition: species.hpp:473
constexpr double PROTON_MASS
Definition: constants.hpp:7
Distribution< Device > f0
Species distribution in velocity space on local mesh nodes.
Definition: species.hpp:120
MPI_Comm SML_COMM_WORLD
Definition: my_mpi.cpp:4
Cabana::AoSoA< ParticleDataTypes, HostType, VEC_LEN > backup_particles
Copy of particles to be restored for RK2.
Definition: species.hpp:116
bool is_electron
Whether this species is the electrons.
Definition: species.hpp:79
void for_all_particles(const std::string label, F lambda_func, const PtlMvmt mvmt, LaunchBounds launch_bounds=LaunchBounds::Default)
Definition: species.hpp:524
void save_backup_particles()
Definition: species.hpp:599
void update_decomposed_f0_calculations(const DomainDecomposition< DeviceType > &pol_decomp, const Grid< DeviceType > &grid, const MagneticField< DeviceType > &magnetic_field, const VelocityGrid &vgrid)
Definition: species.cpp:385
double c2_2m
c2/2m
Definition: species.hpp:87
double rho[VEC_LEN]
Definition: particles.hpp:96
void copy_to_phase0(Species< Device > &species)
Definition: species.hpp:582
Definition: species.hpp:58
Simd< double > w1
Definition: particles.hpp:22
double c_m
c/m
Definition: species.hpp:86
Definition: species.hpp:57
constexpr double EV_2_J
Conversion rate ev to J.
Definition: constants.hpp:5
Definition: velocity_grid.hpp:8
bool default_streaming_option()
Definition: species.hpp:28
Eq::Profile< Device > eq_den
Definition: species.hpp:125
Definition: globals.hpp:89
KOKKOS_INLINE_FUNCTION VecParticles * ptl() const
Definition: species.hpp:574
Definition: grid_weights.hpp:51
KOKKOS_INLINE_FUNCTION double thermal_velocity(double mass, double temp_ev)
Definition: basic_physics.hpp:58
Definition: NamelistReader.hpp:193
KinType kintype
Whether the species is gyrokinetic or drift kinetic.
Definition: species.hpp:82
Definition: magnetic_field.hpp:12
void get_ptl_write_total_and_offsets(const DomainDecomposition< DeviceType > &pol_decomp, long long int &inum_total, long long int &ioff) const
Definition: species.cpp:515
int add_vec_buffer(int n_ptl)
Definition: particles.hpp:194
int idx
Index in all_species.
Definition: species.hpp:78
Definition: particles.hpp:92
int a
The index in the inner array of the AoSoA.
Definition: particles.hpp:150
Definition: particles.hpp:109
KOKKOS_INLINE_FUNCTION void bmag_interpol(const SimdVector &v, Simd< double > &bmag) const
Definition: magnetic_field.tpp:264
bool particles_are_backed_up
Whether particles are currently backed up.
Definition: species.hpp:109
int nonadiabatic_idx
Index of species skipping adiabatic species (for compatibility with fortran arrays) ...
Definition: species.hpp:81
bool default_residence_option()
Definition: species.hpp:35
int n_ptl
Number of particles.
Definition: species.hpp:95
KOKKOS_INLINE_FUNCTION void get_particle_velocity_and_nearest_node(const Grid< DeviceType > &grid, const MagneticField< DeviceType > &magnetic_field, const DomainDecomposition< DeviceType > &pol_decomp, SimdParticles &part, Simd< double > &smu, Simd< double > &vp, Simd< int > &nearest_node, Simd< bool > &not_in_triangle, Simd< bool > &not_in_poloidal_domain) const
Definition: species.hpp:721
Definition: streamed_parallel_for.hpp:16
int node_offset
Offset of first mesh node belonging to this MPI rank.
Definition: domain_decomposition.hpp:49
Definition: streamed_parallel_for.hpp:14
void set_buffer_phase0_d()
Definition: species.hpp:382
long long int get_total_n_ptl()
Definition: species.hpp:671
void set_buffer_particles_d()
Definition: species.hpp:353
Simd< double > rho
Definition: particles.hpp:21
Definition: species.hpp:59
int p_range< DeviceType >(int num_particle)
Definition: particles.hpp:187
int eq_flow_type
Definition: species.hpp:127
double charge_eu
Particle charge in eu.
Definition: species.hpp:85
Definition: species.hpp:51
int nnodes
Number of nodes belonging to this MPI rank.
Definition: domain_decomposition.hpp:50
void resize_particles(int new_n_ptl)
Definition: species.hpp:223
double mass
Particle mass.
Definition: species.hpp:83
KOKKOS_INLINE_FUNCTION double get_f0_eq_thermal_velocity(int inode) const
Definition: species.hpp:704
Species(int idx_in, int nonadiabatic_idx_in, bool is_electron_in, bool is_adiabatic_in, KinType kintype_in, double mass_in, double charge_in, double charge_eu_in, bool is_deltaf_in, int ncycles_in)
Definition: species.cpp:25
void write_ptl_checkpoint_files(const DomainDecomposition< DeviceType > &pol_decomp, const XGC_IO_Stream &stream, std::string sp_name)
Definition: species.cpp:540
void for_all_particles(const std::string label, F lambda_func) const
Definition: species.hpp:406
Cabana::AoSoA< ParticleDataTypes, Device, VEC_LEN > particles_d
Particles on device.
Definition: species.hpp:99
Definition: species.hpp:48
double w2[VEC_LEN]
Definition: particles.hpp:98
#define TIMER(N, F)
Definition: timer_macro.hpp:24
RKRestorationMethod
Definition: species.hpp:68
idx
Definition: diag_f0_df_port1.hpp:32
void copy_particles_to_device_if_not_resident()
Definition: species.hpp:336
void read_ptl_checkpoint_files(const DomainDecomposition< DeviceType > &pol_decomp, const XGC_IO_Stream &stream, std::string sp_name, bool n_ranks_is_same)
Definition: species.cpp:590
RKRestorationMethod RK_restoration_method
Currently, electrons must use first method and ions must use second.
Definition: species.hpp:107
Simd< double > r
Definition: particles.hpp:18
void resize_host_particles_to_match_device()
Definition: species.hpp:243
Definition: species.hpp:69
KOKKOS_INLINE_FUNCTION SimdVector & v()
Definition: particles.hpp:39
ReturnOpt return_opt
Definition: species.hpp:63
ReturnOpt
Definition: species.hpp:56
Option
Definition: streamed_parallel_for.hpp:13
void restore_particles_from_backup()
Definition: species.hpp:620
Definition: globals.hpp:90
static std::vector< MemoryPrediction > estimate_memory_usage(NLReader::NamelistReader &nlr, const Grid< DeviceType > &grid, const DomainDecomposition< DeviceType > &pol_decomp, int species_idx)
Definition: species.cpp:56
SendOpt send_opt
Definition: species.hpp:62
double charge
Particle charge.
Definition: species.hpp:84
SimdPhase ph
Definition: particles.hpp:59
void copy_particles_from_device()
Definition: species.hpp:311
KOKKOS_INLINE_FUNCTION double get_f0_eq_thermal_velocity_lnode(int inode) const
Definition: species.hpp:710
void copy_particles_from_device_if_not_resident()
Definition: species.hpp:342
KOKKOS_INLINE_FUNCTION void wedge_modulo_phi(Simd< double > &phi_mod) const
Definition: grid.tpp:773
void unassign_host_particles()
Definition: species.hpp:260
int ncycles_between_sorts
Number of subcycles between sorts.
Definition: species.hpp:92
Definition: particles.hpp:58
Cabana::AoSoA< PhaseDataTypes, Device, VEC_LEN > phase0_d
Definition: species.hpp:113
int SML_COMM_RANK
Definition: my_mpi.cpp:5
KinType
Definition: globals.hpp:88
Species(SpeciesType sp_type, int n_ptl)
Definition: species.hpp:139
bool is_deltaf
Whether this species is deltaf.
Definition: species.hpp:89
Definition: xgc_io.hpp:19
VecPhase ph
Definition: particles.hpp:110
Definition: species.hpp:44
Definition: species.hpp:70
void set_min_max_num(int isp, int n_ptl)
int minimum_ptl_reservation
The minimum reservation size for particles.
Definition: species.hpp:94
int s
The index in the outer array of the AoSoA.
Definition: particles.hpp:149
KOKKOS_INLINE_FUNCTION double normalized_sqrt_mu(double B, double temp_ev, double mu)
Definition: basic_physics.hpp:90
Simd< double > z
Definition: particles.hpp:19
void copy_particles_to_device_if_resident()
Definition: species.hpp:324
Definition: species.hpp:52
void resize_device_particles(int new_n_ptl)
Definition: species.hpp:281
Definition: species.hpp:53
constexpr double UNIT_CHARGE
Charge of an electron (C)
Definition: constants.hpp:4
long long int get_max_gid() const
Definition: species.cpp:492
KOKKOS_INLINE_FUNCTION double get_f0_eq_thermal_velocity_lnode_h(int inode) const
Definition: species.hpp:716
void exit_XGC(std::string msg)
Definition: globals.hpp:37
void copy_particles_from_device_if_resident()
Definition: species.hpp:330
bool is_adiabatic
Whether this species is adiabatic.
Definition: species.hpp:80
Simd< double > phi
Definition: particles.hpp:20
Definition: magnetic_field.F90:1
static constexpr const Kokkos::Experimental::WorkItemProperty::HintLightWeight_t Async
Definition: space_settings.hpp:82
int n_backup_particles
Definition: species.hpp:117
Eq::Profile< Device > eq_flow
Definition: species.hpp:126
Definition: streamed_parallel_for.hpp:15
SendOpt
Definition: species.hpp:50
void read_f0_checkpoint_files(const DomainDecomposition< DeviceType > &pol_decomp, const XGC_IO_Stream &stream, std::string sp_name)
Definition: species.cpp:685
SimdConstants ct
Definition: particles.hpp:60
void write_f0_checkpoint_files(const DomainDecomposition< DeviceType > &pol_decomp, const XGC_IO_Stream &stream, std::string sp_name)
Definition: species.cpp:649
void copy_particles_to_device()
Definition: species.hpp:295
KOKKOS_INLINE_FUNCTION void restore_phase_from_phase0(const AoSoAIndices< Device > &inds, SimdParticles &part_one) const
Definition: species.hpp:658
Species(int n_ptl_in)
Definition: species.hpp:169
double phi[VEC_LEN]
Definition: particles.hpp:95
Simd< double > w2
Definition: particles.hpp:23
double r[VEC_LEN]
Definition: particles.hpp:93
GyroAverageMatrices< HostType > gyro_avg_matrices
Definition: species.hpp:129
Definition: species.hpp:75
void parallel_for(const std::string name, int n_ptl, Function func, Option option, HostAoSoA aosoa_h, DeviceAoSoA aosoa_d)
Definition: streamed_parallel_for.hpp:252
KOKKOS_INLINE_FUNCTION void get_grid_weights(const MagneticField< Device > &magnetic_field, const SimdVector &v, const Simd< double > &psi, SimdVector2D &xff, SimdGridWeights< Order::One, PIT > &grid_wts) const
Definition: grid.tpp:688
Definition: species.hpp:44
Eq::Profile< Device > eq_temp
Definition: species.hpp:124
bool particles_resident_on_device
Whether the particles can reside on device.
Definition: species.hpp:103
Simd< double > mu
Definition: particles.hpp:52
PtlMvmt(SendOpt send_opt, ReturnOpt return_opt)
Definition: species.hpp:65
static int get_initial_n_ptl(NLReader::NamelistReader &nlr, const Grid< DeviceType > &grid, const DomainDecomposition< DeviceType > &pol_decomp, int sml_special, int species_idx, bool verbose)
Definition: species.cpp:113
int ncycles
Number of subcycles.
Definition: species.hpp:91
Definition: profile.hpp:171
int collision_grid_index
Which collision grid to use.
Definition: species.hpp:122
Definition: particles.hpp:148
SpeciesType
Definition: globals.hpp:83
double z[VEC_LEN]
Definition: particles.hpp:94
void restore_backup_SoA(Cabana::AoSoA< ParticleDataTypes, Device, VEC_LEN > &backup_SoA, int offset, int n) const
Definition: species.hpp:440
Definition: distribution.hpp:10
void resize_device_particles()
Definition: species.hpp:266
int get_max_n_ptl()
Definition: species.hpp:682
LaunchBounds
Definition: species.hpp:395
Cabana::AoSoA< ParticleDataTypes, HostType, VEC_LEN > particles
Particles.
Definition: species.hpp:96
double w1[VEC_LEN]
Definition: particles.hpp:97
Definition: species.hpp:44