-
Notifications
You must be signed in to change notification settings - Fork 36
/
particles.py
2104 lines (1738 loc) · 75.6 KB
/
particles.py
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 ############################### #
# This file is part of the Xtrack Package. #
# Copyright (c) CERN, 2023. #
# ######################################### #
import numpy as np
import xobjects as xo
from pathlib import Path
from .constants import PROTON_MASS_EV
from scipy.constants import e as qe
from scipy.constants import c as clight
from scipy.constants import epsilon_0
from xobjects import BypassLinked
LAST_INVALID_STATE = -999999999
class Particles(xo.HybridClass):
_cname = 'ParticlesData'
size_vars = (
(xo.Int64, '_capacity'),
(xo.Int64, '_num_active_particles'),
(xo.Int64, '_num_lost_particles'),
(xo.Int64, 'start_tracking_at_element'),
)
# Capacity is always kept up to date
# the other two are placeholders to be used if needed
# i.e. on ContextCpu
scalar_vars = (
(xo.Float64, 'q0'),
(xo.Float64, 'mass0'),
)
part_energy_vars = (
(xo.Float64, 'ptau'),
(xo.Float64, 'delta'),
(xo.Float64, 'rpp'),
(xo.Float64, 'rvv'),
)
per_particle_vars = (
(
(xo.Float64, 'p0c'),
(xo.Float64, 'gamma0'),
(xo.Float64, 'beta0'),
(xo.Float64, 's'),
(xo.Float64, 'zeta'),
(xo.Float64, 'x'),
(xo.Float64, 'y'),
(xo.Float64, 'px'),
(xo.Float64, 'py'),
)
+ part_energy_vars +
(
(xo.Float64, 'chi'),
(xo.Float64, 'charge_ratio'),
(xo.Float64, 'weight'),
(xo.Int64, 'pdg_id'),
(xo.Int64, 'particle_id'),
(xo.Int64, 'at_element'),
(xo.Int64, 'at_turn'),
(xo.Int64, 'state'),
(xo.Int64, 'parent_particle_id'),
(xo.UInt32, '_rng_s1'),
(xo.UInt32, '_rng_s2'),
(xo.UInt32, '_rng_s3'),
(xo.UInt32, '_rng_s4')
)
)
_xofields = {
**{nn: tt for tt, nn in size_vars + scalar_vars},
**{nn: tt[:] for tt, nn in per_particle_vars},
}
_extra_c_sources = [
Path(__file__).parent.joinpath('rng_src', 'base_rng.h'),
Path(__file__).parent.joinpath('rng_src', 'particles_rng.h'),
'\n /*placeholder_for_local_particle_src*/ \n'
]
_rename = {
'delta': '_delta',
'ptau': '_ptau',
'rvv': '_rvv',
'rpp': '_rpp',
'p0c': '_p0c',
'gamma0': '_gamma0',
'beta0': '_beta0',
}
_kernels = {
'Particles_initialize_rand_gen': xo.Kernel(
args=[
xo.Arg(xo.ThisClass, name='particles'),
xo.Arg(xo.UInt32, pointer=True, name='seeds'),
xo.Arg(xo.Int32, name='n_init')],
n_threads='n_init')
}
def __init__(
self,
_capacity=None,
_no_reorganize=False,
**kwargs,
):
"""
The Particles class contains coordinates and other data associated to a
set of particles. Parameters can be provided as arrays of the same
length or as scalars. If arrays are provided, the length of the arrays
must be equal to the number of particles. If scalars are provided, the
same value is assigned to all particles. When parameters are not
provided, they are initialized to default values, or inferred from the
other parameters.
Parameters
----------
_capacity: int
The maximum number of particles that can be stored in the object.
If not provided, it is inferred from the size of the provided
coordinates arrays.
s : array_like of float, optional
Reference accumulated path length [m]
x : array_like of float, optional
Horizontal position [m]
px : array_like of float, optional
Px / (m/m0 * p0c) = beta_x gamma /(beta0 gamma0)
y : array_like of float, optional
Vertical position [m]
py : array_like of float, optional
Py / (m/m0 * p0c)
delta : array_like of float, optional
(Pc m0/m - p0c) /p0c
ptau : array_like of float, optional
(Energy m0/m - Energy0) / p0c
pzeta : array_like of float, optional
ptau / beta0
rvv : array_like of float, optional
beta / beta0
rpp : array_like of float, optional
m/m0 P0c / Pc = 1/(1+delta)
zeta : array_like of float, optional
(s - beta0 c t)
tau : array_like of float, optional
(s / beta0 - ct)
mass0 : float, optional
Reference rest mass [eV]
q0 : float, optional
Reference charge [e]
p0c : array_like of float, optional
Reference momentum [eV]
energy0 : array_like of float, optional
Reference energy [eV]
gamma0 : array_like of float, optional
Reference relativistic gamma
beta0 : array_like of float, optional
Reference relativistic beta
mass_ratio : array_like of float, optional
mass/mass0 (this is used to track particles of
different species. Note that mass is the rest mass
of the considered particle species and not the
relativistic mass)
chi : array_like of float, optional
q / q0 * m0 / m = qratio / mratio
charge_ratio : array_like of float, optional
q / q0
particle_id : array_like of int, optional
Identifier of the particle
at_turn : array_like of int, optional
Number of tracked turns
state : array_like of int, optional
It is <= 0 if the particle is lost, > 0 otherwise
(different values are used to record information on how the particle
is lost or generated)
pdg_id : array_like of float, optional
PDG id of the particle under consideration (needed when tracking
ions to distinguish different particle types). The default is 0
(undefined)
weight : array_like of float, optional
Particle weight in number of particles (for collective simulations)
at_element : array_like of int, optional
Identifier of the last element through which the particle has been
parent_particle_id : array_like of int, optional
Identifier of the parent particle (secondary production processes)
"""
if '_xobject' in kwargs.keys():
# Initialize xobject
self.xoinitialize(**kwargs)
return
if 'sigma' in kwargs.keys():
raise NameError('`sigma` is not supported anymore. '
'Please use `zeta` instead.')
if 'psigma' in kwargs.keys():
raise NameError('`psigma` is not supported anymore.'
'Please use `pzeta` instead.')
per_part_input_vars = (
self.per_particle_vars +
((xo.Float64, 'energy0'),
(xo.Float64, 'tau'),
(xo.Float64, 'pzeta'),
(xo.Float64, 'mass_ratio'))
)
# Determine the number of particles and the capacity, so we can allocate
# the xobject of the right size
input_length = 1
for _, field in per_part_input_vars:
if field not in kwargs.keys():
continue
if np.isscalar(kwargs[field]) or len(kwargs[field]) == 1:
continue
if len(kwargs[field]) != input_length and input_length > 1:
raise ValueError(
'All per particle vars have to be of the '
'same length.'
)
input_length = len(kwargs[field])
# Validate _capacity if given explicitly, if not assume it based on input
if _capacity is not None:
if _capacity <= 0:
raise ValueError('Explicitly provided `_capacity` has to be'
'greater than zero.')
if _capacity < input_length:
raise ValueError(
f'Capacity ({_capacity}) has to be greater or equal to the '
f'number of particles ({input_length}).'
)
else:
_capacity = input_length
# Allocate the xobject of the right size
self.xoinitialize(
_context=kwargs.pop('_context', None),
_buffer=kwargs.pop('_buffer', None),
_offset=kwargs.pop('_offset', None),
**{field: _capacity for _, field in self.per_particle_vars}
)
self._capacity = _capacity
self._num_active_particles = -1 # To be filled in only on CPU
self._num_lost_particles = -1 # To be filled in only on CPU
# Initialize the fields to preset values
for type_, field in self.per_particle_vars:
raw_field = self._rename.get(field, field)
if raw_field.startswith('_rng'):
setattr(self, raw_field, 0)
else:
setattr(self, raw_field, LAST_INVALID_STATE)
np_to_ctx = self._context.nparray_to_context_array
# Mask out the unallocated space from now on
# (match the length of the input arrays)
self.hide_first_n_particles(input_length)
# Start populating the object with the input values
state = kwargs.get('state', 1)
if np.isscalar(state) or len(state) == 1:
state = np.array(state).item()
else:
state = np_to_ctx(np.array(state))
self.state = state
input_mask = self.state > LAST_INVALID_STATE
particle_ids = kwargs.get('particle_id', np.arange(input_length))
particle_ids = np.atleast_1d(particle_ids)
self.particle_id = np_to_ctx(particle_ids)
parent_particle_id = np.atleast_1d(kwargs.get('parent_particle_id',
particle_ids))
self.parent_particle_id = np_to_ctx(parent_particle_id)
for field in ('state', 'particle_id', 'parent_particle_id'):
kwargs.pop(field, None)
# Init scalar vars
self.q0 = kwargs.get('q0', 1.0)
self.mass0 = kwargs.get('mass0', PROTON_MASS_EV)
self.start_tracking_at_element = kwargs.get(
'start_tracking_at_element', -1)
# Init refs
if 'kinetic_energy0' in kwargs.keys():
assert kwargs.get('energy0') is None
kwargs['energy0'] = kwargs.pop('kinetic_energy0') + self.mass0
# Ensure that all per particle inputs are numpy arrays of the same
# length, and move them to the target context
for xotype, field in per_part_input_vars:
if field not in kwargs.keys():
continue
if np.isscalar(kwargs[field]) or len(kwargs[field]) == 1:
value = np.array(kwargs[field]).item()
kwargs[field] = np.full(input_length, value)
else:
kwargs[field] = np.array(kwargs[field])
# Coerce the right type so that we can allocate the right array
# in the target context. PyOpenCL gets fussy if types don't match
# in calculations.
if kwargs[field].dtype != xotype._dtype:
kwargs[field] = kwargs[field].astype(xotype._dtype)
kwargs[field] = np_to_ctx(kwargs[field])
# Init independent per particle vars
self.init_independent_per_part_vars(kwargs)
self._update_refs(
p0c=kwargs.get('p0c'),
energy0=kwargs.get('energy0'),
gamma0=kwargs.get('gamma0'),
beta0=kwargs.get('beta0'),
mask=input_mask,
)
# Init energy deviations
self._update_energy_deviations(
delta=kwargs.get('delta'),
ptau=kwargs.get('ptau'),
pzeta=kwargs.get('pzeta'),
_rpp=kwargs.get('rpp'),
_rvv=kwargs.get('rvv'),
mask=input_mask,
)
# Init zeta
self._update_zeta(
zeta=kwargs.get('zeta'),
tau=kwargs.get('tau'),
mask=input_mask,
)
# Init chi and charge ratio
self._update_chi_charge_ratio(
chi=kwargs.get('chi'),
charge_ratio=kwargs.get('charge_ratio'),
mass_ratio=kwargs.get('mass_ratio'),
mask=input_mask,
)
self.unhide_first_n_particles()
if isinstance(self._context, xo.ContextCpu) and not _no_reorganize:
self.reorganize()
@classmethod
def from_dict(cls, dct, load_rng_state=True, **kwargs):
"""
Create a new Particles object from a dictionary.
Parameters
----------
dct : dict
The dictionary to load the Particles object from.
load_rng_state : bool, optional
Whether to load the state of the random number generator from the
dictionary. Defaults to True.
_context : Context, optional
The context to load the Particles object into. If not provided,
the xobjects default context will be used.
_buffer : Buffer, optional
The buffer to load the Particles object into. If not provided,
a new buffer will be allocated from the context.
Returns
-------
particles : Particles
The newly created Particles object.
"""
part = cls(**dct, **kwargs)
np_to_ctx = part._context.nparray_to_context_array
def array_to_ctx(ary, default=0):
if ary is not None and not np.isscalar(ary):
return np_to_ctx(np.array(ary, dtype='uint32'))
else:
return ary or default
if load_rng_state:
part._rng_s1 = array_to_ctx(dct.get('_rng_s1'))
part._rng_s2 = array_to_ctx(dct.get('_rng_s2'))
part._rng_s3 = array_to_ctx(dct.get('_rng_s3'))
part._rng_s4 = array_to_ctx(dct.get('_rng_s4'))
return part
def to_dict(self, copy_to_cpu=True,
remove_underscored=None,
remove_unused_space=None,
remove_redundant_variables=None,
keep_rng_state=None,
compact=False):
"""
Convert the Particles object to a dictionary.
Parameters
----------
copy_to_cpu : bool, optional
Whether to copy the Particles object to the CPU before converting
it to a dictionary. Defaults to True.
compact:
Whether to minimize the size of the dictionary. Defaults to False.
remove_underscored : bool, optional
Whether to remove underscored variables from the dictionary.
Defaults to True.
remove_unused_space : bool, optional
Whether to remove unused space from the arrays. Defaults to
the value of `compact`.
remove_redundant_variables : bool, optional
Whether to remove redundant variables from the dictionary.
Defaults to the value of `compact`.
keep_rng_state : bool, optional
Whether to keep the state of the random number generator in the
dictionary. Defaults to true if `compact` is False.
Returns
-------
dct : dict
The dictionary containing the data from Particles object.
"""
if remove_underscored is None:
remove_underscored = True
if remove_unused_space is None:
remove_unused_space = compact
if remove_redundant_variables is None:
remove_redundant_variables = compact
if keep_rng_state is None:
keep_rng_state = not compact
p_for_dict = self
if copy_to_cpu:
p_for_dict = p_for_dict.copy(_context=xo.context_default)
if remove_unused_space:
p_for_dict = p_for_dict.remove_unused_space()
dct = xo.HybridClass.to_dict(p_for_dict)
dct['delta'] = p_for_dict.delta
dct['ptau'] = p_for_dict.ptau
dct['rvv'] = p_for_dict.rvv
dct['rpp'] = p_for_dict.rpp
dct['p0c'] = p_for_dict._p0c
dct['beta0'] = p_for_dict._beta0
dct['gamma0'] = p_for_dict._gamma0
dct['start_tracking_at_element'] = p_for_dict.start_tracking_at_element
if remove_underscored:
for kk in list(dct.keys()):
if kk.startswith('_'):
if keep_rng_state and kk.startswith('_rng'):
continue
del (dct[kk])
if remove_redundant_variables:
for kk in ['ptau', 'rpp', 'rvv', 'gamma0', 'beta0']:
del (dct[kk])
return dct
@classmethod
def from_pandas(cls, df, _context=None, _buffer=None, _offset=None):
"""
Create a new Particles object from a pandas DataFrame.
Parameters
----------
df : pandas.DataFrame
The DataFrame to load the Particles object from.
_context : Context, optional
The context to load the Particles object into. If not provided,
the xobjects default context will be used.
_buffer : Buffer, optional
The buffer to load the Particles object into. If not provided,
a new buffer will be allocated from the context.
Returns
-------
particles : Particles
The newly created Particles object.
"""
dct = df.to_dict(orient='list')
for tt, nn in cls.scalar_vars + cls.size_vars:
if nn in dct.keys() and not np.isscalar(dct[nn]):
dct[nn] = dct[nn][0]
return cls(**dct, _context=_context, _buffer=_buffer, _offset=_offset)
def to_pandas(self,
remove_underscored=None,
remove_unused_space=None,
remove_redundant_variables=None,
keep_rng_state=None,
compact=False):
"""
Convert the Particles object to a pandas DataFrame.
Parameters
----------
compact:
Whether to minimize the size of the dictionary. Defaults to False.
remove_underscored : bool, optional
Whether to remove underscored variables from the dictionary.
Defaults to True.
remove_unused_space : bool, optional
Whether to remove unused space from the arrays. Defaults to
the value of `compact`.
remove_redundant_variables : bool, optional
Whether to remove redundant variables from the dictionary.
Defaults to the value of `compact`.
keep_rng_state : bool, optional
Whether to keep the state of the random number generator in the
dictionary. Defaults to true if `compact` is False.
Returns
-------
df : pandas.DataFrame
The DataFrame containing the data from Particles object.
"""
dct = self.to_dict(
remove_underscored=remove_underscored,
remove_unused_space=remove_unused_space,
remove_redundant_variables=remove_redundant_variables,
keep_rng_state=keep_rng_state,
compact=compact)
import pandas as pd
return pd.DataFrame(dct)
def to_table(self):
"""
Get a Table object with the Particles coordinates.
Returns
-------
table : Table
The Table object containing the data from Particles object.
"""
import xtrack as xt
out_dct = self.to_dict(compact=False)
for kk in list(out_dct.keys()):
if not hasattr(out_dct[kk], '__len__'):
out_dct.pop(kk)
elif len(out_dct[kk]) != len(out_dct['particle_id']):
out_dct.pop(kk)
# Prettier ordering
col_names = ['s', 'x', 'px', 'y', 'py', 'zeta', 'delta', 'particle_id']
for nn in col_names.copy():
if nn not in out_dct.keys():
col_names.remove(nn)
col_names += [kk for kk in out_dct.keys() if kk not in col_names]
return xt.Table(out_dct, index='particle_id', col_names=col_names)
def get_table(self):
"""
Get a Table object with the Particles coordinates.
Returns
-------
table : Table
The Table object containing the data from Particles object.
"""
return self.to_table()
@classmethod
def merge(cls, lst, _context=None, _buffer=None, _offset=None):
"""
Merge a list of Particles objects into a single one.
Parameters
----------
lst : list of Particles
The list of Particles objects to merge.
_context : Context, optional
The context to load the Particles object into. If not provided,
the xobjects default context will be used.
_buffer : Buffer, optional
The buffer to load the Particles object into. If not provided,
a new buffer will be allocated from the context.
Returns
-------
particles : Particles
The newly created Particles object.
"""
# TODO For now the merge is performed on CPU for add contexts.
# Slow for objects on GPU (transferred to CPU for the merge).
# Move everything to cpu
cpu_lst = []
for pp in lst:
assert isinstance(pp, cls)
if isinstance(pp._buffer.context, xo.ContextCpu):
cpu_lst.append(pp)
else:
cpu_lst.append(pp.copy(_context=xo.context_default))
# Check that scalar variable are compatible
for tt, nn in cls.scalar_vars:
vals = [getattr(pp, nn) for pp in cpu_lst]
assert np.allclose(vals, getattr(cpu_lst[0], nn),
rtol=0, atol=1e-14)
# Make new particle on CPU
capacity = np.sum([pp._capacity for pp in cpu_lst])
new_part_cpu = cls(_capacity=capacity)
# Copy scalar vars from first particle
for tt, nn in cls.scalar_vars:
setattr(new_part_cpu, nn, getattr(cpu_lst[0], nn))
# Copy per-particle vars
first = 0
max_id_curr = -1
with new_part_cpu._bypass_linked_vars():
for pp in cpu_lst:
for tt, nn in cls.per_particle_vars:
if not (nn == 'particle_id' or nn == 'parent_id'):
getattr(new_part_cpu, nn)[
first:first + pp._capacity] = getattr(pp, nn)
# Handle particle_ids and parent_ids
mask = pp.particle_id >= 0
new_id = pp.particle_id.copy()
new_parent_id = pp.parent_particle_id.copy()
if np.min(new_id[mask]) <= max_id_curr:
new_id[mask] += (max_id_curr + 1)
new_parent_id[mask] += (max_id_curr + 1)
new_part_cpu.particle_id[first:first + len(new_id)] = new_id
new_part_cpu.parent_particle_id[
first:first + len(new_id)] = new_parent_id
max_id_curr = np.max(new_id)
first += pp._capacity
# Reorganize
new_part_cpu.reorganize()
# Copy to appropriate context
if _context is None and _buffer is None:
# Use constext of first particle
if isinstance(lst[0]._buffer.context, xo.ContextCpu):
new_part_cpu._buffer.context = lst[0]._buffer.context
return new_part_cpu
else:
return new_part_cpu.copy(_context=lst[0]._buffer.context)
else:
return new_part_cpu.copy(_context=_context, _buffer=_buffer,
_offset=_offset)
def filter(self, mask):
"""
Select a subset of particles satisfying a logical condition.
Parameters
----------
mask : array of bool
The logical condition to apply to the particles.
Returns
-------
particles : Particles
The newly created Particles object.
"""
if isinstance(self._buffer.context, xo.ContextCpu):
self_cpu = self
else:
self_cpu = self.copy(_context=xo.context_default)
# copy mask to cpu is needed
if isinstance(mask, self._buffer.context.nplike_array_type):
mask = self._buffer.context.nparray_from_context_array(mask)
# Pyopencl returns int8 instead of bool
if (isinstance(self._buffer.context, xo.ContextPyopencl) and
mask.dtype == np.int8):
assert np.all((mask >= 0) & (mask <= 1))
mask = mask > 0
# Make new particle on CPU
test_x = self_cpu.x[mask]
capacity = len(test_x)
new_part_cpu = self.__class__(_capacity=capacity)
# Copy scalar vars from first particle
for tt, nn in self.scalar_vars:
setattr(new_part_cpu, nn, getattr(self_cpu, nn))
# Copy per-particle vars
for tt, nn in self.per_particle_vars:
with new_part_cpu._bypass_linked_vars():
getattr(new_part_cpu, nn)[:] = getattr(self_cpu, nn)[mask]
# Reorganize
new_part_cpu.reorganize()
# Copy to original context
target_ctx = self._buffer.context
if isinstance(target_ctx, xo.ContextCpu):
new_part_cpu._buffer.context = target_ctx
return new_part_cpu
else:
return new_part_cpu.copy(_context=target_ctx)
def sort(self, by='particle_id', interleave_lost_particles=False):
"""
Sort the particles by a given variable.
Parameters
----------
by : str
The name of the variable to sort by. Default is 'particle_id'.
interleave_lost_particles : bool
If True, lost particles are interleaved with active particles.
If False, lost particles are moved to the end of the array.
Returns
-------
sorted_index : array of int
The index of the sorted particles.
"""
if not isinstance(self._buffer.context, xo.ContextCpu):
raise NotImplementedError('Sorting only works on CPU for now')
if self.lost_particles_are_hidden:
restore_hidden = True
self.unhide_lost_particles()
else:
restore_hidden = False
n_active, n_lost = self.reorganize()
n_used = n_active + n_lost
sort_key_var = getattr(self, by)[:n_used].copy()
if not interleave_lost_particles:
max_id_active = np.max(self.particle_id[:n_active])
sort_key_var[n_active:] = 10 + max_id_active + sort_key_var[n_active:]
sorted_index = np.argsort(sort_key_var)
with self._bypass_linked_vars():
for tt, nn in self.per_particle_vars:
vv = getattr(self, nn)
vv[:n_used] = vv[:n_used][sorted_index]
if interleave_lost_particles:
self._num_active_particles = -2
self._num_lost_particles = -2
elif restore_hidden:
self.hide_lost_particles(_assume_reorganized=True)
def reorganize(self):
"""
Reorganize the particles object so that all active particles are at the
beginning of the arrays.
Returns
-------
n_active : int
The number of active particles.
n_lost : int
The number of lost particles.
"""
if self.lost_particles_are_hidden:
restore_hidden = True
self.unhide_lost_particles()
else:
restore_hidden = False
if isinstance(self._context, xo.ContextPyopencl):
# Needs special treatment because masking does not work with pyopencl
# Going to for the masking for now, could be replaced by a kernel in the future.
state_cpu = self.state.get()
mask_active_cpu = state_cpu > 0
mask_lost_cpu = (state_cpu < 1) & (state_cpu > LAST_INVALID_STATE)
mask_active = self._context.nparray_to_context_array(
np.where(mask_active_cpu)[0])
mask_lost = self._context.nparray_to_context_array(
np.where(mask_lost_cpu)[0])
n_active = int(np.sum(mask_active_cpu))
n_lost = int(np.sum(mask_lost_cpu))
needs_reorganization = not mask_active_cpu[:n_active].all()
else:
mask_active = self.state > 0
mask_lost = (self.state < 1) & (self.state > LAST_INVALID_STATE)
n_active = int(np.sum(mask_active))
n_lost = int(np.sum(mask_lost))
needs_reorganization = not mask_active[:n_active].all()
if needs_reorganization:
# Reorganize particles
with self._bypass_linked_vars():
for tt, nn in self.per_particle_vars:
vv = getattr(self, nn)
vv_active = vv[mask_active]
vv_lost = vv[mask_lost]
vv[:n_active] = vv_active
vv[n_active:n_active + n_lost] = vv_lost
if nn.startswith('_rng'):
vv[n_active + n_lost:] = 0
else:
vv[n_active + n_lost:] = tt._dtype.type(LAST_INVALID_STATE)
if isinstance(self._buffer.context, xo.ContextCpu):
self._num_active_particles = n_active
self._num_lost_particles = n_lost
if restore_hidden:
self.hide_lost_particles(_assume_reorganized=True)
return n_active, n_lost
def hide_lost_particles(self, _assume_reorganized=False):
"""
Hide lost particles in the particles object.
"""
self._lim_arrays_name = '_num_active_particles'
if not _assume_reorganized:
n_active, _ = self.reorganize()
self._num_active_particles = n_active
def unhide_lost_particles(self):
"""
Unhide lost particles in the particles object.
"""
if hasattr(self, '_lim_arrays_name'):
del self._lim_arrays_name
if not isinstance(self._context, xo.ContextCpu):
self._num_active_particles = -1
def remove_unused_space(self):
"""
Return a new particles object with removed unused space in the
particle arrays (when the number of particles is smaller than the
capacity of the particles object).
"""
return self.filter(self.state > LAST_INVALID_STATE)
def add_particles(self, part, keep_lost=False):
"""
Add particles to the particles object.
Parameters
----------
part : Particles
The particles to add.
keep_lost : bool, optional
If True, lost particles are also added. Default is False.
"""
if keep_lost:
raise NotImplementedError
assert not isinstance(self._buffer.context, xo.ContextPyopencl), (
'Masking does not work with pyopencl')
mask_copy = part.state > 0
n_copy = np.sum(mask_copy)
n_active, n_lost = self.reorganize()
i_start_copy = n_active + n_lost
n_free = self._capacity - n_active - n_lost
max_id = np.max(self.particle_id[:n_active + n_lost])
if n_copy > n_free:
raise NotImplementedError("Out of space, need to regenerate xobject")
for tt, nn in self.scalar_vars:
assert np.isclose(getattr(self, nn), getattr(part, nn),
rtol=1e-14, atol=1e-14)
with self._bypass_linked_vars():
for tt, nn in self.per_particle_vars:
if nn.startswith('_rng'):
continue
vv = getattr(self, nn)
vv_copy = getattr(part, nn)[mask_copy]
vv[i_start_copy:i_start_copy + n_copy] = vv_copy
new_ids = self._context.nplike_lib.arange(
int(max_id) + 1, int(max_id) + 1 + int(n_copy), dtype=np.int64)
self.particle_id[i_start_copy:i_start_copy + n_copy] = new_ids
self.reorganize()
def get_active_particle_id_range(self):
"""
Get the range of particle ids of active particles.
"""
ctx2np = self._buffer.context.nparray_from_context_array
mask_active = ctx2np(self.state) > 0
ids_active_particles = ctx2np(self.particle_id)[mask_active]
# Behaves as python range (+1)
return np.min(ids_active_particles), np.max(ids_active_particles) + 1
def init_pipeline(self, name):
self.name = name
def show(self):
"""
Print particle properties.
"""
df = self.to_pandas()
dash = '-' * 55
print("PARTICLES:\n\n")
print('{:<27} {:>12}'.format("Property", "Value"))
print(dash)
for column in df:
print('{:<27} {:>12}'.format(df[column].name, df[column].values[0]))
print(dash)
print('\n')
def get_classical_particle_radius0(self):
"""
Get classical particle radius of the reference particle.
"""
m0 = self.mass0 * qe / (clight ** 2) # electron volt - kg conversion
r0 = (self.q0 * qe) ** 2 / (4 * np.pi * epsilon_0 * m0 * clight ** 2) # 1.5347e-18 is default for protons
return r0
def _bypass_linked_vars(self):
return BypassLinked(self)
def _has_valid_rng_state(self):
# I check only the first particle
if (self._xobject._rng_s1[0] == 0
and self._xobject._rng_s2[0] == 0
and self._xobject._rng_s3[0] == 0
and self._xobject._rng_s4[0] == 0):
return False
else:
return True
def _init_random_number_generator(self, seeds=None):
"""
Initialize state of the random number generator (possibility to providing
a seed for each particle).
"""
self.compile_kernels(only_if_needed=True)
if seeds is None: