-
Notifications
You must be signed in to change notification settings - Fork 276
Expand file tree
/
Copy pathpicmi.py
More file actions
5639 lines (4629 loc) · 228 KB
/
Copy pathpicmi.py
File metadata and controls
5639 lines (4629 loc) · 228 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2018-2022 Andrew Myers, David Grote, Ligia Diana Amorim
# Maxence Thevenet, Remi Lehe, Revathi Jambunathan, Lorenzo Giacomel
#
#
# This file is part of WarpX.
#
# License: BSD-3-Clause-LBNL
"""Classes following the PICMI standard"""
import os
import re
from dataclasses import dataclass
import numpy as np
import periodictable
import picmistandard
import pywarpx
import pywarpx.callbacks
codename = "warpx"
picmistandard.register_codename(codename)
# dictionary to map field boundary conditions from picmistandard to WarpX
BC_map = {
"open": "pml",
"dirichlet": "pec",
"periodic": "periodic",
"damped": "damped",
"absorbing_silver_mueller": "absorbing_silver_mueller",
"neumann": "neumann",
"none": "none",
None: "none",
}
class constants:
# --- Put the constants in their own namespace
# --- Values from WarpXConst.H
c = 299792458.0
ep0 = 8.8541878188e-12
mu0 = 1.2566370612685e-06
q_e = 1.602176634e-19
m_e = 9.1093837139e-31
m_p = 1.67262192595e-27
hbar = 1.0545718176461565e-34
kb = 1.380649e-23
picmistandard.register_constants(constants)
def _set_refined_region_inputs(refined_regions):
if refined_regions:
assert len(refined_regions) == 1, Exception(
"WarpX only supports one refined region."
)
assert refined_regions[0][0] == 1, Exception(
"The one refined region can only be level 1"
)
pywarpx.amr.max_level = 1
pywarpx.warpx.fine_tag_lo = refined_regions[0][1]
pywarpx.warpx.fine_tag_hi = refined_regions[0][2]
if len(refined_regions[0]) == 4:
pywarpx.amr.ref_ratio_vect = refined_regions[0][3]
else:
pywarpx.amr.max_level = 0
class Species(picmistandard.PICMI_Species):
"""
See `Input Parameters <https://warpx.readthedocs.io/en/latest/usage/parameters.html>`__ for more information.
Parameters
----------
warpx_boost_adjust_transverse_positions: bool, default=False
Whether to adjust transverse positions when apply the boost
to the simulation frame
warpx_self_fields_required_precision: float, default=1.e-11
Relative precision on the electrostatic solver
(when using the relativistic solver)
warpx_self_fields_absolute_tolerance: float, default=0.
Absolute precision on the electrostatic solver
(when using the relativistic solver)
warpx_self_fields_max_iters: integer, default=200
Maximum number of iterations for the electrostatic
solver for the species
warpx_self_fields_verbosity: integer, default=2
Level of verbosity for the electrostatic solver
warpx_save_previous_position: bool, default=False
Whether to save the old particle positions
warpx_do_not_deposit: bool, default=False
Whether or not to deposit the charge and current density for
for this species
warpx_do_not_push: bool, default=False
Whether or not to push this species
warpx_do_not_gather: bool, default=False
Whether or not to gather the fields from grids for this species
warpx_radial_numpercell_power: float, default=0.
With cylindrical geometry, specifies the radial power of the number of particles per cell
warpx_random_theta: bool, default=True
Whether or not to add random angle to the particles in theta
when in RZ mode.
warpx_reflection_model_xlo: string, default='0.'
Expression (in terms of the velocity "v") specifying the probability
that the particle will reflect on the lower x boundary
warpx_reflection_model_xhi: string, default='0.'
Expression (in terms of the velocity "v") specifying the probability
that the particle will reflect on the upper x boundary
warpx_reflection_model_ylo: string, default='0.'
Expression (in terms of the velocity "v") specifying the probability
that the particle will reflect on the lower y boundary
warpx_reflection_model_yhi: string, default='0.'
Expression (in terms of the velocity "v") specifying the probability
that the particle will reflect on the upper y boundary
warpx_reflection_model_zlo: string, default='0.'
Expression (in terms of the velocity "v") specifying the probability
that the particle will reflect on the lower z boundary
warpx_reflection_model_zhi: string, default='0.'
Expression (in terms of the velocity "v") specifying the probability
that the particle will reflect on the upper z boundary
warpx_save_particles_at_xlo: bool, default=False
Whether to save particles lost at the lower x boundary
warpx_save_particles_at_xhi: bool, default=False
Whether to save particles lost at the upper x boundary
warpx_save_particles_at_ylo: bool, default=False
Whether to save particles lost at the lower y boundary
warpx_save_particles_at_yhi: bool, default=False
Whether to save particles lost at the upper y boundary
warpx_save_particles_at_zlo: bool, default=False
Whether to save particles lost at the lower z boundary
warpx_save_particles_at_zhi: bool, default=False
Whether to save particles lost at the upper z boundary
warpx_save_particles_at_eb: bool, default=False
Whether to save particles lost at the embedded boundary
warpx_do_resampling: bool, default=False
Whether particles will be resampled
warpx_resampling_min_ppc: int, default=1
Cells with fewer particles than this number will be
skipped during resampling.
warpx_resampling_algorithm_target_weight: float
Weight that the product particles from resampling will not exceed.
warpx_resampling_trigger_intervals: bool, default=0
Timesteps at which to resample
warpx_resampling_trigger_max_avg_ppc: int, default=infinity
Resampling will be done when the average number of
particles per cell exceeds this number
warpx_resampling_algorithm_target_ratio: float, default=1.5
Roughly corresponds to the ratio between the number of particles before
and after resampling. Only used with the `leveling_thinning` algorithm.
warpx_resampling_algorithm: str, default="leveling_thinning"
Resampling algorithm to use.
warpx_resampling_algorithm_velocity_grid_type: str, default="spherical"
Type of grid to use when clustering particles in velocity space. Only
applicable with the `velocity_coincidence_thinning` algorithm.
warpx_resampling_algorithm_delta_ur: float
Size of velocity window used for clustering particles during grid-based
merging, with `velocity_grid_type == "spherical"`.
warpx_resampling_algorithm_n_theta: int
Number of bins to use in theta when clustering particle velocities
during grid-based merging, with `velocity_grid_type == "spherical"`.
warpx_resampling_algorithm_n_phi: int
Number of bins to use in phi when clustering particle velocities
during grid-based merging, with `velocity_grid_type == "spherical"`.
warpx_resampling_algorithm_delta_u: array of floats or float
Size of velocity window used in ux, uy and uz for clustering particles
during grid-based merging, with `velocity_grid_type == "cartesian"`. If
a single number is given the same du value will be used in all three
directions.
warpx_add_int_attributes: dict
Dictionary of extra integer particle attributes initialized from an
expression that is a function of the variables (x, y, z, ux, uy, uz, t).
warpx_add_real_attributes: dict
Dictionary of extra real particle attributes initialized from an
expression that is a function of the variables (x, y, z, ux, uy, uz, t).
warpx_do_temperature_deposition: bool, default=False
This flag is set per species to do another pass to deposit temperature
on each timestep if required. Currently only works with Ohm's Law Hybrid Solver.
"""
def init(self, kw):
self.species_type = None
if self.particle_type in [
"unspecified",
"electron",
"positron",
"muon",
"antimuon",
"photon",
"neutron",
"proton",
"antiproton",
"alpha",
]:
self.species_type = self.particle_type
else:
if self.charge is None and self.charge_state is not None:
self.charge = f"{self.charge_state}*q_e"
if self.particle_type is not None:
# Match a string of the format '#nXx', with the '#n' optional isotope number.
m = re.match(r"(?P<iso>#[\d+])*(?P<sym>[A-Za-z]+)", self.particle_type)
if m is not None:
element = periodictable.elements.symbol(m["sym"])
if m["iso"] is not None:
element = element[m["iso"][1:]]
if self.charge_state is not None:
assert self.charge_state <= element.number, Exception(
"%s charge state not valid" % self.particle_type
)
try:
element = element.ion[self.charge_state]
except ValueError:
# Note that not all valid charge states are defined in elements,
# so this value error can be ignored.
pass
self.element = element
if self.mass is None:
self.mass = (
element.mass * periodictable.constants.atomic_mass_constant
)
else:
raise Exception('The species "particle_type" is not known')
self.boost_adjust_transverse_positions = kw.pop(
"warpx_boost_adjust_transverse_positions", None
)
# For the relativistic electrostatic solver
self.self_fields_required_precision = kw.pop(
"warpx_self_fields_required_precision", None
)
self.self_fields_absolute_tolerance = kw.pop(
"warpx_self_fields_absolute_tolerance", None
)
self.self_fields_max_iters = kw.pop("warpx_self_fields_max_iters", None)
self.self_fields_verbosity = kw.pop("warpx_self_fields_verbosity", None)
self.save_previous_position = kw.pop("warpx_save_previous_position", None)
self.do_not_deposit = kw.pop("warpx_do_not_deposit", None)
self.do_not_push = kw.pop("warpx_do_not_push", None)
self.do_not_gather = kw.pop("warpx_do_not_gather", None)
self.radial_numpercell_power = kw.pop("warpx_radial_numpercell_power", None)
self.random_theta = kw.pop("warpx_random_theta", None)
# For particle reflection
self.reflection_model_xlo = kw.pop("warpx_reflection_model_xlo", None)
self.reflection_model_xhi = kw.pop("warpx_reflection_model_xhi", None)
self.reflection_model_ylo = kw.pop("warpx_reflection_model_ylo", None)
self.reflection_model_yhi = kw.pop("warpx_reflection_model_yhi", None)
self.reflection_model_zlo = kw.pop("warpx_reflection_model_zlo", None)
self.reflection_model_zhi = kw.pop("warpx_reflection_model_zhi", None)
# self.reflection_model_eb = kw.pop('warpx_reflection_model_eb', None)
# For the scraper buffer
self.save_particles_at_xlo = kw.pop("warpx_save_particles_at_xlo", None)
self.save_particles_at_xhi = kw.pop("warpx_save_particles_at_xhi", None)
self.save_particles_at_ylo = kw.pop("warpx_save_particles_at_ylo", None)
self.save_particles_at_yhi = kw.pop("warpx_save_particles_at_yhi", None)
self.save_particles_at_zlo = kw.pop("warpx_save_particles_at_zlo", None)
self.save_particles_at_zhi = kw.pop("warpx_save_particles_at_zhi", None)
self.save_particles_at_eb = kw.pop("warpx_save_particles_at_eb", None)
# Resampling settings
self.do_resampling = kw.pop("warpx_do_resampling", None)
self.resampling_algorithm = kw.pop("warpx_resampling_algorithm", None)
self.resampling_min_ppc = kw.pop("warpx_resampling_min_ppc", None)
self.resampling_trigger_intervals = kw.pop(
"warpx_resampling_trigger_intervals", None
)
self.resampling_triggering_max_avg_ppc = kw.pop(
"warpx_resampling_trigger_max_avg_ppc", None
)
self.resampling_algorithm_target_ratio = kw.pop(
"warpx_resampling_algorithm_target_ratio", None
)
self.resampling_algorithm_target_weight = kw.pop(
"warpx_resampling_algorithm_target_weight", None
)
self.resampling_algorithm_velocity_grid_type = kw.pop(
"warpx_resampling_algorithm_velocity_grid_type", None
)
self.resampling_algorithm_delta_ur = kw.pop(
"warpx_resampling_algorithm_delta_ur", None
)
self.resampling_algorithm_n_theta = kw.pop(
"warpx_resampling_algorithm_n_theta", None
)
self.resampling_algorithm_n_phi = kw.pop(
"warpx_resampling_algorithm_n_phi", None
)
self.resampling_algorithm_delta_u = kw.pop(
"warpx_resampling_algorithm_delta_u", None
)
if (
self.resampling_algorithm_delta_u is not None
and np.size(self.resampling_algorithm_delta_u) == 1
):
self.resampling_algorithm_delta_u = [self.resampling_algorithm_delta_u] * 3
# extra particle attributes
self.extra_int_attributes = kw.pop("warpx_add_int_attributes", None)
self.extra_real_attributes = kw.pop("warpx_add_real_attributes", None)
self.do_temperature_deposition = kw.pop("warpx_do_temperature_deposition", None)
def species_initialize_inputs(
self,
layout,
initialize_self_fields=False,
injection_plane_position=None,
injection_plane_normal_vector=None,
):
self.species_number = len(pywarpx.particles.species_names)
if self.name is None:
self.name = "species{}".format(self.species_number)
pywarpx.particles.species_names.append(self.name)
if initialize_self_fields is None:
initialize_self_fields = False
self.species = pywarpx.Bucket.Bucket(
self.name,
species_type=self.species_type,
mass=self.mass,
charge=self.charge,
injection_style=None,
initialize_self_fields=int(initialize_self_fields),
boost_adjust_transverse_positions=self.boost_adjust_transverse_positions,
self_fields_required_precision=self.self_fields_required_precision,
self_fields_absolute_tolerance=self.self_fields_absolute_tolerance,
self_fields_max_iters=self.self_fields_max_iters,
self_fields_verbosity=self.self_fields_verbosity,
save_particles_at_xlo=self.save_particles_at_xlo,
save_particles_at_xhi=self.save_particles_at_xhi,
save_particles_at_ylo=self.save_particles_at_ylo,
save_particles_at_yhi=self.save_particles_at_yhi,
save_particles_at_zlo=self.save_particles_at_zlo,
save_particles_at_zhi=self.save_particles_at_zhi,
save_particles_at_eb=self.save_particles_at_eb,
save_previous_position=self.save_previous_position,
do_not_deposit=self.do_not_deposit,
do_not_push=self.do_not_push,
do_not_gather=self.do_not_gather,
radial_numpercell_power=self.radial_numpercell_power,
random_theta=self.random_theta,
do_resampling=self.do_resampling,
resampling_algorithm=self.resampling_algorithm,
resampling_min_ppc=self.resampling_min_ppc,
resampling_trigger_intervals=self.resampling_trigger_intervals,
resampling_trigger_max_avg_ppc=self.resampling_triggering_max_avg_ppc,
resampling_algorithm_target_ratio=self.resampling_algorithm_target_ratio,
resampling_algorithm_target_weight=self.resampling_algorithm_target_weight,
resampling_algorithm_velocity_grid_type=self.resampling_algorithm_velocity_grid_type,
resampling_algorithm_delta_ur=self.resampling_algorithm_delta_ur,
resampling_algorithm_n_theta=self.resampling_algorithm_n_theta,
resampling_algorithm_n_phi=self.resampling_algorithm_n_phi,
resampling_algorithm_delta_u=self.resampling_algorithm_delta_u,
do_temperature_deposition=self.do_temperature_deposition,
)
# add reflection models
self.species.add_new_attr("reflection_model_xlo(E)", self.reflection_model_xlo)
self.species.add_new_attr("reflection_model_xhi(E)", self.reflection_model_xhi)
self.species.add_new_attr("reflection_model_ylo(E)", self.reflection_model_ylo)
self.species.add_new_attr("reflection_model_yhi(E)", self.reflection_model_yhi)
self.species.add_new_attr("reflection_model_zlo(E)", self.reflection_model_zlo)
self.species.add_new_attr("reflection_model_zhi(E)", self.reflection_model_zhi)
# self.species.add_new_attr("reflection_model_eb(E)", self.reflection_model_eb)
# extra particle attributes
if self.extra_int_attributes is not None:
self.species.addIntegerAttributes = self.extra_int_attributes.keys()
for attr, function in self.extra_int_attributes.items():
self.species.add_new_attr(
"attribute." + attr + "(x,y,z,ux,uy,uz,t)", function
)
if self.extra_real_attributes is not None:
self.species.addRealAttributes = self.extra_real_attributes.keys()
for attr, function in self.extra_real_attributes.items():
self.species.add_new_attr(
"attribute." + attr + "(x,y,z,ux,uy,uz,t)", function
)
pywarpx.Particles.particles_list.append(self.species)
if self.initial_distribution is not None:
distributions_is_list = np.iterable(self.initial_distribution)
layout_is_list = np.iterable(layout)
if not distributions_is_list and not layout_is_list:
self.initial_distribution.distribution_initialize_inputs(
self.species_number, layout, self.species, self.density_scale, ""
)
elif distributions_is_list and (layout_is_list or layout is None):
assert layout is None or (
len(self.initial_distribution) == len(layout)
), Exception(
"The initial distribution and layout lists must have the same lenth"
)
source_names = [
f"dist{i}" for i in range(len(self.initial_distribution))
]
self.species.injection_sources = source_names
for i, dist in enumerate(self.initial_distribution):
layout_i = layout[i] if layout is not None else None
dist.distribution_initialize_inputs(
self.species_number,
layout_i,
self.species,
self.density_scale,
source_names[i],
)
else:
raise Exception(
"The initial distribution and layout must both be scalars or both be lists"
)
if injection_plane_position is not None:
if injection_plane_normal_vector is not None:
assert (
injection_plane_normal_vector[0] == 0.0
and injection_plane_normal_vector[1] == 0.0
), Exception("Rigid injection can only be done along z")
pywarpx.particles.rigid_injected_species.append(self.name)
self.species.rigid_advance = 1
self.species.zinject_plane = injection_plane_position
picmistandard.PICMI_MultiSpecies.Species_class = Species
class MultiSpecies(picmistandard.PICMI_MultiSpecies):
def species_initialize_inputs(
self,
layout,
initialize_self_fields=False,
injection_plane_position=None,
injection_plane_normal_vector=None,
):
for species in self.species_instances_list:
species.species_initialize_inputs(
layout,
initialize_self_fields,
injection_plane_position,
injection_plane_normal_vector,
)
class GaussianBunchDistribution(picmistandard.PICMI_GaussianBunchDistribution):
def init(self, kw):
self.do_symmetrize = kw.pop("warpx_do_symmetrize", None)
self.symmetrization_order = kw.pop("warpx_symmetrization_order", None)
def distribution_initialize_inputs(
self, species_number, layout, species, density_scale, source_name
):
species.add_new_group_attr(source_name, "injection_style", "gaussian_beam")
species.add_new_group_attr(source_name, "x_m", self.centroid_position[0])
species.add_new_group_attr(source_name, "y_m", self.centroid_position[1])
species.add_new_group_attr(source_name, "z_m", self.centroid_position[2])
species.add_new_group_attr(source_name, "x_rms", self.rms_bunch_size[0])
species.add_new_group_attr(source_name, "y_rms", self.rms_bunch_size[1])
species.add_new_group_attr(source_name, "z_rms", self.rms_bunch_size[2])
# --- Only PseudoRandomLayout is supported
species.add_new_group_attr(source_name, "npart", layout.n_macroparticles)
# --- Total number of real particles
species.add_new_group_attr(source_name, "npart_real", self.n_physical_particles)
if density_scale is not None:
species.add_new_group_attr(source_name, "npart_real", density_scale)
# --- The PICMI standard doesn't yet have a way of specifying these values.
# --- They should default to the size of the domain. They are not typically
# --- necessary though since any particles outside the domain are rejected.
# species.xmin
# species.xmax
# species.ymin
# species.ymax
# species.zmin
# species.zmax
# --- Note that WarpX takes gamma*beta as input
if np.any(np.not_equal(self.velocity_divergence, 0.0)):
u_over_x = self.velocity_divergence[0] / constants.c
u_over_y = self.velocity_divergence[1] / constants.c
u_over_z = self.velocity_divergence[2] / constants.c
species.add_new_group_attr(
source_name, "momentum_distribution_type", "parse_momentum_function"
)
species.add_new_group_attr(
source_name, "momentum_function_ux(x,y,z)", f"{u_over_x}*x"
)
species.add_new_group_attr(
source_name, "momentum_function_uy(x,y,z)", f"{u_over_y}*y"
)
species.add_new_group_attr(
source_name, "momentum_function_uz(x,y,z)", f"{u_over_z}*z"
)
elif np.any(np.not_equal(self.rms_velocity, 0.0)):
species.add_new_group_attr(
source_name, "momentum_distribution_type", "gaussian"
)
species.add_new_group_attr(
source_name, "ux_m", self.centroid_velocity[0] / constants.c
)
species.add_new_group_attr(
source_name, "uy_m", self.centroid_velocity[1] / constants.c
)
species.add_new_group_attr(
source_name, "uz_m", self.centroid_velocity[2] / constants.c
)
species.add_new_group_attr(
source_name, "ux_th", self.rms_velocity[0] / constants.c
)
species.add_new_group_attr(
source_name, "uy_th", self.rms_velocity[1] / constants.c
)
species.add_new_group_attr(
source_name, "uz_th", self.rms_velocity[2] / constants.c
)
else:
species.add_new_group_attr(
source_name, "momentum_distribution_type", "constant"
)
species.add_new_group_attr(
source_name, "ux", self.centroid_velocity[0] / constants.c
)
species.add_new_group_attr(
source_name, "uy", self.centroid_velocity[1] / constants.c
)
species.add_new_group_attr(
source_name, "uz", self.centroid_velocity[2] / constants.c
)
species.add_new_group_attr(source_name, "do_symmetrize", self.do_symmetrize)
species.add_new_group_attr(
source_name, "symmetrization_order", self.symmetrization_order
)
class DensityDistributionBase(object):
"""This is a base class for several predefined density distributions. It
captures universal initialization logic."""
def set_mangle_dict(self):
if not hasattr(self, "mangle_dict"):
self.mangle_dict = None
if hasattr(self, "user_defined_kw") and self.mangle_dict is None:
# Only do this once so that the same variables can be used multiple
# times
self.mangle_dict = pywarpx.my_constants.add_keywords(self.user_defined_kw)
def set_species_attributes(self, species, layout, source_name):
if isinstance(layout, GriddedLayout):
# --- Note that the grid attribute of GriddedLayout is ignored
species.add_new_group_attr(
source_name, "injection_style", "nuniformpercell"
)
species.add_new_group_attr(
source_name,
"num_particles_per_cell_each_dim",
layout.n_macroparticle_per_cell,
)
elif isinstance(layout, PseudoRandomLayout):
assert layout.n_macroparticles_per_cell is not None, Exception(
"WarpX only supports n_macroparticles_per_cell for the PseudoRandomLayout with this distribution"
)
species.add_new_group_attr(source_name, "injection_style", "nrandompercell")
species.add_new_group_attr(
source_name, "num_particles_per_cell", layout.n_macroparticles_per_cell
)
else:
raise Exception(
"WarpX does not support the specified layout for this distribution"
)
species.add_new_group_attr(source_name, "xmin", self.lower_bound[0])
species.add_new_group_attr(source_name, "xmax", self.upper_bound[0])
species.add_new_group_attr(source_name, "ymin", self.lower_bound[1])
species.add_new_group_attr(source_name, "ymax", self.upper_bound[1])
species.add_new_group_attr(source_name, "zmin", self.lower_bound[2])
species.add_new_group_attr(source_name, "zmax", self.upper_bound[2])
if self.fill_in:
species.add_new_group_attr(source_name, "do_continuous_injection", 1)
if hasattr(self, "momentum_spread_expressions") and np.any(
np.not_equal(self.momentum_spread_expressions, None)
):
species.add_new_group_attr(
source_name, "momentum_distribution_type", "maxwellian"
)
# Mean drift: any axis left as None falls back to directed_velocity.
species.add_new_group_attr(
source_name, "maxwellian_u_mean_distribution_type", "parser"
)
self.setup_parse_momentum_functions(
species,
source_name,
self.momentum_expressions,
self.directed_velocity,
"u{dir}_mean_function(x,y,z)",
)
# Thermal spread: any axis left as None falls back to zero.
species.add_new_group_attr(
source_name, "maxwellian_u_std_distribution_type", "parser"
)
self.setup_parse_momentum_functions(
species,
source_name,
self.momentum_spread_expressions,
[0.0, 0.0, 0.0],
"u{dir}_std_function(x,y,z)",
)
elif hasattr(self, "momentum_expressions") and np.any(
np.not_equal(self.momentum_expressions, None)
):
species.add_new_group_attr(
source_name, "momentum_distribution_type", "parse_momentum_function"
)
self.setup_parse_momentum_functions(
species,
source_name,
self.momentum_expressions,
self.directed_velocity,
"momentum_function_u{dir}(x,y,z)",
)
elif np.any(np.not_equal(self.rms_velocity, 0.0)):
species.add_new_group_attr(
source_name, "momentum_distribution_type", "gaussian"
)
species.add_new_group_attr(
source_name, "ux_m", self.directed_velocity[0] / constants.c
)
species.add_new_group_attr(
source_name, "uy_m", self.directed_velocity[1] / constants.c
)
species.add_new_group_attr(
source_name, "uz_m", self.directed_velocity[2] / constants.c
)
species.add_new_group_attr(
source_name, "ux_th", self.rms_velocity[0] / constants.c
)
species.add_new_group_attr(
source_name, "uy_th", self.rms_velocity[1] / constants.c
)
species.add_new_group_attr(
source_name, "uz_th", self.rms_velocity[2] / constants.c
)
else:
species.add_new_group_attr(
source_name, "momentum_distribution_type", "constant"
)
species.add_new_group_attr(
source_name, "ux", self.directed_velocity[0] / constants.c
)
species.add_new_group_attr(
source_name, "uy", self.directed_velocity[1] / constants.c
)
species.add_new_group_attr(
source_name, "uz", self.directed_velocity[2] / constants.c
)
if hasattr(self, "density_min"):
species.add_new_group_attr(source_name, "density_min", self.density_min)
if hasattr(self, "density_max"):
species.add_new_group_attr(source_name, "density_max", self.density_max)
def setup_parse_momentum_functions(
self, species, source_name, expressions, defaults, attr_pattern
):
"""Write per-component momentum parser expressions (divided by c) to the species.
``attr_pattern`` is a format string with a ``{dir}`` placeholder for the
component, e.g. ``"momentum_function_u{dir}(x,y,z)"`` for the
``parse_momentum_function`` distribution or ``"u{dir}_mean_function(x,y,z)"``
and ``"u{dir}_std_function(x,y,z)"`` for the ``maxwellian`` distribution.
"""
for sdir, idir in zip(["x", "y", "z"], [0, 1, 2]):
if expressions[idir] is not None:
expression = pywarpx.my_constants.mangle_expression(
expressions[idir], self.mangle_dict
)
else:
expression = f"{defaults[idir]}"
species.add_new_group_attr(
source_name,
attr_pattern.format(dir=sdir),
f"({expression})/{constants.c}",
)
class UniformDistribution(
picmistandard.PICMI_UniformDistribution, DensityDistributionBase
):
def distribution_initialize_inputs(
self, species_number, layout, species, density_scale, source_name
):
self.set_mangle_dict()
self.set_species_attributes(species, layout, source_name)
# --- Only constant density is supported by this class
species.add_new_group_attr(source_name, "profile", "constant")
species.add_new_group_attr(source_name, "density", self.density)
if density_scale is not None:
species.add_new_group_attr(source_name, "density", density_scale)
class FluxDistributionBase(object):
"""This is a base class for both uniform and analytic flux distributions."""
def init(self, kw):
self.inject_from_embedded_boundary = kw.pop(
"warpx_inject_from_embedded_boundary", False
)
def initialize_flux_profile_func(self, species, density_scale, source_name):
"""Initialize the flux profile and flux function."""
pass
def distribution_initialize_inputs(
self, species_number, layout, species, density_scale, source_name
):
self.fill_in = False
self.set_mangle_dict()
self.set_species_attributes(species, layout, source_name)
self.initialize_flux_profile_func(species, density_scale, source_name)
if not self.inject_from_embedded_boundary:
species.add_new_group_attr(
source_name, "flux_normal_axis", self.flux_normal_axis
)
species.add_new_group_attr(
source_name, "surface_flux_pos", self.surface_flux_position
)
species.add_new_group_attr(
source_name, "flux_direction", self.flux_direction
)
else:
species.add_new_group_attr(
source_name, "inject_from_embedded_boundary", True
)
species.add_new_group_attr(source_name, "flux_tmin", self.flux_tmin)
species.add_new_group_attr(source_name, "flux_tmax", self.flux_tmax)
# --- Use specific attributes for flux injection
species.add_new_group_attr(source_name, "injection_style", "nfluxpercell")
assert isinstance(layout, PseudoRandomLayout), Exception(
"UniformFluxDistribution only supports the PseudoRandomLayout in WarpX"
)
if self.gaussian_flux_momentum_distribution:
species.add_new_group_attr(
source_name, "momentum_distribution_type", "gaussianflux"
)
class AnalyticFluxDistribution(
picmistandard.PICMI_AnalyticFluxDistribution,
FluxDistributionBase,
DensityDistributionBase,
):
"""
Parameters
----------
warpx_inject_from_embedded_boundary: bool
When true, the flux is injected from the embedded boundaries instead
of a plane.
"""
def init(self, kw):
FluxDistributionBase.init(self, kw)
def initialize_flux_profile_func(self, species, density_scale, source_name):
species.add_new_group_attr(source_name, "flux_profile", "parse_flux_function")
if density_scale is not None:
species.add_new_group_attr(source_name, "flux", density_scale)
expression = pywarpx.my_constants.mangle_expression(self.flux, self.mangle_dict)
if density_scale is None:
species.add_new_group_attr(
source_name, "flux_function(x,y,z,t)", expression
)
else:
species.add_new_group_attr(
source_name,
"flux_function(x,y,z,t)",
"{}*({})".format(density_scale, expression),
)
class UniformFluxDistribution(
picmistandard.PICMI_UniformFluxDistribution,
FluxDistributionBase,
DensityDistributionBase,
):
"""
Parameters
----------
warpx_inject_from_embedded_boundary: bool
When true, the flux is injected from the embedded boundaries instead
of a plane.
"""
def init(self, kw):
FluxDistributionBase.init(self, kw)
def initialize_flux_profile_func(self, species, density_scale, source_name):
species.add_new_group_attr(source_name, "flux_profile", "constant")
species.add_new_group_attr(source_name, "flux", self.flux)
if density_scale is not None:
species.add_new_group_attr(source_name, "flux", density_scale)
class AnalyticDistribution(
picmistandard.PICMI_AnalyticDistribution, DensityDistributionBase
):
"""
Parameters
----------
warpx_density_min: float
Minimum plasma density. No particle is injected where the density is
below this value.
warpx_density_max: float
Maximum plasma density. The density at each point is the minimum between
the value given in the profile, and density_max.
warpx_momentum_spread_expressions: list of string
Analytic expressions describing the gamma*velocity spread for each axis [m/s].
Expressions should be in terms of the position, written as 'x', 'y', and 'z'.
Parameters can be used in the expression with the values given as keyword arguments.
For any axis not supplied (set to None), zero will be used.
"""
def init(self, kw):
self.density_min = kw.pop("warpx_density_min", None)
self.density_max = kw.pop("warpx_density_max", None)
self.momentum_spread_expressions = kw.pop(
"warpx_momentum_spread_expressions", [None, None, None]
)
def distribution_initialize_inputs(
self, species_number, layout, species, density_scale, source_name
):
self.set_mangle_dict()
self.set_species_attributes(species, layout, source_name)
species.add_new_group_attr(source_name, "profile", "parse_density_function")
expression = pywarpx.my_constants.mangle_expression(
self.density_expression, self.mangle_dict
)
if density_scale is None:
species.add_new_group_attr(
source_name, "density_function(x,y,z)", expression
)
else:
species.add_new_group_attr(
source_name,
"density_function(x,y,z)",
"{}*({})".format(density_scale, expression),
)
class ParticleListDistribution(picmistandard.PICMI_ParticleListDistribution):
def init(self, kw):
pass
def distribution_initialize_inputs(
self, species_number, layout, species, density_scale, source_name
):
species.add_new_group_attr(source_name, "injection_style", "multipleparticles")
species.add_new_group_attr(source_name, "multiple_particles_pos_x", self.x)
species.add_new_group_attr(source_name, "multiple_particles_pos_y", self.y)
species.add_new_group_attr(source_name, "multiple_particles_pos_z", self.z)
species.add_new_group_attr(
source_name, "multiple_particles_ux", np.array(self.ux) / constants.c
)
species.add_new_group_attr(
source_name, "multiple_particles_uy", np.array(self.uy) / constants.c
)
species.add_new_group_attr(
source_name, "multiple_particles_uz", np.array(self.uz) / constants.c
)
species.add_new_group_attr(
source_name, "multiple_particles_weight", self.weight
)
if density_scale is not None:
species.add_new_group_attr(
source_name, "multiple_particles_weight", self.weight * density_scale
)
class FromFileDistribution(picmistandard.PICMI_FromFileDistribution):
def init(self, kw):
pass
def distribution_initialize_inputs(
self, species_number, layout, species, density_scale, source_name
):
species.add_new_group_attr(source_name, "injection_style", "external_file")
species.add_new_group_attr(source_name, "injection_file", self.file_path)
class ParticleDistributionPlanarInjector(
picmistandard.PICMI_ParticleDistributionPlanarInjector
):
pass
class GriddedLayout(picmistandard.PICMI_GriddedLayout):
pass
class PseudoRandomLayout(picmistandard.PICMI_PseudoRandomLayout):
def init(self, kw):
if self.seed is not None:
print(
"Warning: WarpX does not support specifying the random number seed in PseudoRandomLayout"
)
class BinomialSmoother(picmistandard.PICMI_BinomialSmoother):
def smoother_initialize_inputs(self, solver):
pywarpx.warpx.use_filter = 1
pywarpx.warpx.use_filter_compensation = bool(np.all(self.compensation))
if self.n_pass is None:
# If not specified, do at least one pass in each direction.
self.n_pass = 1
try:
# Check if n_pass is a vector
len(self.n_pass)
except TypeError:
# If not, make it a vector
self.n_pass = solver.grid.number_of_dimensions * [self.n_pass]
pywarpx.warpx.filter_npass_each_dir = self.n_pass
class CylindricalGrid(picmistandard.PICMI_CylindricalGrid):
"""
This assumes that WarpX was compiled with USE_RZ = TRUE
See `Input Parameters <https://warpx.readthedocs.io/en/latest/usage/parameters.html>`__ for more information.
Parameters
----------
warpx_max_grid_size: integer, default=32
Maximum block size in either direction
warpx_max_grid_size_x: integer, optional
Maximum block size in radial direction
warpx_max_grid_size_y: integer, optional
Maximum block size in longitudinal direction
warpx_blocking_factor: integer, optional