-
Notifications
You must be signed in to change notification settings - Fork 306
/
particle_class.py
2601 lines (2137 loc) · 83.4 KB
/
particle_class.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
"""Classes to represent particles."""
from __future__ import annotations
__all__ = [
"AbstractParticle",
"AbstractPhysicalParticle",
"CustomParticle",
"DimensionlessParticle",
"Particle",
"ParticleLike",
"molecule",
"valid_categories",
]
import astropy.constants as const
import astropy.units as u
import json
import numpy as np
import warnings
from abc import ABC, abstractmethod
from collections import defaultdict, namedtuple
from datetime import datetime
from numbers import Integral, Real
from typing import NoReturn, Optional, TYPE_CHECKING, Union
from plasmapy.particles import _elements, _isotopes, _parsing, _special_particles
from plasmapy.particles.exceptions import (
ChargeError,
InvalidElementError,
InvalidIonError,
InvalidIsotopeError,
InvalidParticleError,
MissingParticleDataError,
MissingParticleDataWarning,
ParticleError,
ParticleWarning,
)
from plasmapy.utils import roman
from plasmapy.utils._units_helpers import _get_physical_type_dict
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
_classification_categories = {
"lepton",
"antilepton",
"fermion",
"boson",
"antibaryon",
"baryon",
"neutrino",
"antineutrino",
"matter",
"antimatter",
"stable",
"unstable",
"charged",
"uncharged",
"custom",
}
_periodic_table_categories = {
"nonmetal",
"metal",
"alkali metal",
"alkaline earth metal",
"metalloid",
"transition metal",
"post-transition metal",
"halogen",
"noble gas",
"actinide",
"lanthanide",
}
_atomic_property_categories = {"element", "isotope", "ion"}
_specific_particle_categories = {"electron", "positron", "proton", "neutron"}
valid_categories = (
_periodic_table_categories
| _classification_categories
| _atomic_property_categories
| _specific_particle_categories
)
r"""
A `set` containing all valid particle categories.
See Also
--------
:py:meth:`~plasmapy.particles.particle_class.AbstractPhysicalParticle.is_category`
"""
def _category_errmsg(particle, category: str) -> str:
"""
Return an error message when an attribute raises an
`~plasmapy.particles.exceptions.InvalidElementError`,
`~plasmapy.particles.exceptions.InvalidIonError`, or
`~plasmapy.particles.exceptions.InvalidIsotopeError`.
"""
article = "an" if category[0] in "aeiouAEIOU" else "a"
return (
f"The particle {particle} is not {article} {category}, so this "
f"attribute is not available."
)
class AbstractParticle(ABC):
"""An abstract base class that defines the interface for particles."""
@property
@abstractmethod
def mass(self) -> Union[u.Quantity, Real]:
"""Provide the particle's mass."""
raise NotImplementedError
@property
@abstractmethod
def charge(self) -> Union[u.Quantity, Real]:
"""Provide the particle's electric charge."""
raise NotImplementedError
@property
def json_dict(self) -> dict:
"""
A dictionary representation of the particle object that is JSON
friendly (i.e. convertible to a JSON object).
The dictionary should maintain the following format so that
`~plasmapy.particles.serialization.ParticleJSONDecoder` knows
how to decode the resulting JSON object.
.. code-block:: python
{
"plasmapy_particle": {
# string representation of the particle class
"type": "Particle",
# string representation of the module contains the particle class
"module": "plasmapy.particles.particle_class",
# date stamp of when the object was created
"date_created": "2020-07-20 17:46:13 UTC",
# parameters used to initialized the particle class
"__init__": {
# tuple of positional arguments
"args": (),
# dictionary of keyword arguments
"kwargs": {},
},
}
}
Only the ``"__init__"`` entry should be modified by the subclass.
"""
return {
"plasmapy_particle": {
"type": type(self).__name__,
"module": self.__module__,
"date_created": datetime.utcnow().strftime( # noqa: DTZ003
"%Y-%m-%d %H:%M:%S UTC"
),
"__init__": {"args": (), "kwargs": {}},
}
}
def __bool__(self):
"""
Raise an `~plasmapy.particles.exceptions.ParticleError` because
particles do not have a truth value.
"""
raise ParticleError("The truth value of a particle is not defined.")
def json_dump(self, fp, **kwargs):
"""
Write the particle's `json_dict` to the ``fp`` file object using
`json.dump`.
Parameters
----------
fp: `file object <https://docs.python.org/3/glossary.html#term-file-object>`_
Destination file object to write the JSON serialized `json_dict`.
**kwargs:
Any keyword accepted by `json.dump`.
"""
return json.dump(self.json_dict, fp, **kwargs)
def json_dumps(self, **kwargs) -> str:
"""
Serialize the particle's `json_dict` into a JSON formatted `str`
using `json.dumps`.
Parameters
----------
**kwargs:
Any keyword accepted by `json.dumps`.
Returns
-------
str
JSON formatted `str`.
"""
return json.dumps(self.json_dict, **kwargs)
class AbstractPhysicalParticle(AbstractParticle):
"""Base class for particles that are defined with physical units."""
@property
def _as_particle_list(self):
# Avoid circular imports by importing here
from plasmapy.particles.particle_collections import ParticleList
return ParticleList([self])
@property
@abstractmethod
def categories(self) -> set[str]:
"""Provide the particle's categories."""
...
def is_category(
self,
*category_tuple,
require: Optional[Union[str, Iterable[str]]] = None,
any_of: Optional[Union[str, Iterable[str]]] = None,
exclude: Optional[Union[str, Iterable[str]]] = None,
) -> bool:
"""Determine if the particle meets categorization criteria.
Return `True` if the particle is consistent with the provided
categories, and `False` otherwise.
Parameters
----------
*category_tuple
Required categories in the form of one or more `str` objects
or an iterable.
require : `str` or iterable of `str`, |keyword-only|, optional
One or more particle categories. This method will return
`False` if the particle does not belong to all of these
categories.
any_of : `str` or iterable of `str`, |keyword-only|, optional
One or more particle categories. This method will return
`False` if the particle does not belong to at least one of
these categories.
exclude : `str` or iterable of `str`, |keyword-only|, optional
One or more particle categories. This method will return
`False` if the particle belongs to any of these categories.
See Also
--------
~plasmapy.particles.particle_class.valid_categories :
A `set` containing all valid particle categories.
Notes
-----
Valid particle categories are given in
`~plasmapy.particles.particle_class.valid_categories` and
include: ``"actinide"``, ``"alkali metal"``, ``"alkaline earth
metal"``, ``"antibaryon"``, ``"antilepton"``, ``"antimatter"``,
``"antineutrino"``, ``"baryon"``, ``"boson"``, ``"charged"``,
``"custom"``, ``"electron"``, ``"element"``, ``"fermion"``,
``"halogen"``, ``"ion"``, ``"isotope"``, ``"lanthanide"``,
``"lepton"``, ``"matter"``, ``"metal"``, ``"metalloid"``,
``"neutrino"``, ``"neutron"``, ``"noble gas"``, ``"nonmetal"``,
``"positron"``, ``"post-transition metal"``, ``"proton"``,
``"stable"``, ``"transition metal"``, ``"uncharged"``, and
``"unstable"``.
Examples
--------
Required categories may be entered as positional arguments,
including as a `list`, `set`, or `tuple` of required categories.
>>> electron = Particle("e-")
>>> electron.is_category("lepton")
True
>>> electron.is_category("lepton", "baryon")
False
>>> electron.is_category(["fermion", "matter"])
True
Required arguments may also be provided using the ``require``
keyword argument.
>>> electron.is_category(require="lepton")
True
>>> electron.is_category(require=["lepton", "baryon"])
False
This method will return `False` if the particle does not belong
to at least one of the categories provided with the ``any_of``
keyword argument.
>>> electron.is_category(any_of=["lepton", "baryon"])
True
>>> electron.is_category(any_of=("noble gas", "lanthanide", "halogen"))
False
This method will return `False` if the particle belongs to any
of the categories provided in the ``exclude`` keyword argument.
>>> electron.is_category(exclude="baryon")
True
>>> electron.is_category(exclude={"lepton", "baryon"})
False
The ``require``, ``any_of``, and ``exclude`` keywords may be
combined. If the particle matches all of the provided criteria,
then this method will return `True`.
>>> electron.is_category(
... require="fermion", any_of={'lepton', 'baryon'}, exclude='charged',
... )
False
"""
def become_set(arg: Union[str, set, Sequence]) -> set[str]:
"""Change the argument into a `set`."""
if arg is None:
return set()
if isinstance(arg, set):
return arg
if isinstance(arg, str):
return {arg}
return set(arg[0]) if isinstance(arg[0], (tuple, list, set)) else set(arg)
if category_tuple and require:
raise ParticleError(
"No positional arguments are allowed if the `require` keyword "
"is set in is_category."
)
require = become_set(category_tuple) if category_tuple else become_set(require)
exclude = become_set(exclude)
any_of = become_set(any_of)
invalid_categories = (require | exclude | any_of) - valid_categories
duplicate_categories = require & exclude | exclude & any_of | require & any_of
categories_and_adjectives = [
(invalid_categories, "invalid"),
(duplicate_categories, "duplicated"),
]
for problem_categories, adjective in categories_and_adjectives:
if problem_categories:
raise ParticleError(
f"The following categories in {self.__repr__()}"
f".is_category are {adjective}: {problem_categories}"
)
if exclude and exclude & self.categories:
return False
if any_of and not any_of & self.categories:
return False
return require <= self.categories
def __add__(self, other):
return self._as_particle_list + other
def __radd__(self, other):
return other + self._as_particle_list
def __mul__(self, other):
return self._as_particle_list.__mul__(other)
def __rmul__(self, other):
return self._as_particle_list.__mul__(other)
def __gt__(self, other):
return self._as_particle_list.__gt__(other)
class Particle(AbstractPhysicalParticle):
"""
A class for an individual particle or antiparticle.
Parameters
----------
argument : |particle-like|
A string representing a particle, element, isotope, or ion; an
integer representing the atomic number of an element; or a
|Particle|.
mass_numb : integer, |keyword-only|, optional
The mass number of an isotope.
Z : integer, |keyword-only|, optional
The |charge number| of an ion or neutral atom.
Raises
------
`TypeError`
For when any of the arguments or keywords is not of the required
type.
`~plasmapy.particles.exceptions.InvalidParticleError`
Raised when the particle input does not correspond to a valid
particle or is contradictory.
`~plasmapy.particles.exceptions.InvalidElementError`
For when an attribute is being accessed that requires
information about an element, but the particle is not an
element, isotope, or ion.
`~plasmapy.particles.exceptions.InvalidIsotopeError`
For when an attribute is being accessed that requires
information about an isotope or nuclide, but the particle is not
an isotope (or an ion of an isotope).
`~plasmapy.particles.exceptions.ChargeError`
For when either the
`~plasmapy.particles.particle_class.Particle.charge` or
`~plasmapy.particles.particle_class.Particle.charge_number`
attributes is being accessed but the charge information for the
particle is not available.
`~plasmapy.particles.exceptions.ParticleError`
Raised for attempts at converting a
|Particle| object to a `bool`.
See Also
--------
~plasmapy.particles.particle_class.CustomParticle
~plasmapy.particles.particle_class.DimensionlessParticle
~plasmapy.particles.particle_collections.ParticleList
~plasmapy.particles.particle_class.valid_categories
Notes
-----
Valid particle categories include: ``"actinide"``, ``"alkali
metal"``, ``"alkaline earth metal"``, ``"antibaryon"``,
``"antilepton"``, ``"antimatter"``, ``"antineutrino"``,
``"baryon"``, ``"boson"``, ``"charged"``, ``"custom"``,
``"electron"``, ``"element"``, ``"fermion"``, ``"halogen"``,
``"ion"``, ``"isotope"``, ``"lanthanide"``, ``"lepton"``,
``"matter"``, ``"metal"``, ``"metalloid"``, ``"neutrino"``,
``"neutron"``, ``"noble gas"``, ``"nonmetal"``, ``"positron"``,
``"post-transition metal"``, ``"proton"``, ``"stable"``,
``"transition metal"``, ``"uncharged"``, and ``"unstable"``.
Examples
--------
Particles may be defined using a wide variety of aliases:
>>> proton = Particle('p+')
>>> electron = Particle('e-')
>>> neutron = Particle('neutron')
>>> deuteron = Particle('D', Z=1)
>>> triton = Particle('T+')
>>> alpha = Particle('He', mass_numb=4, Z=2)
>>> positron = Particle('positron')
>>> hydrogen = Particle(1) # atomic number
The `~plasmapy.particles.particle_class.Particle.symbol` attribute
returns the particle's symbol in the standard form.
>>> positron.symbol
'e+'
The `~plasmapy.particles.particle_class.Particle.element`,
`~plasmapy.particles.particle_class.Particle.isotope`, and
`~plasmapy.particles.particle_class.Particle.ionic_symbol` attributes
provide the symbols for each of these different types of particles.
>>> proton.element
'H'
>>> alpha.isotope
'He-4'
>>> deuteron.ionic_symbol
'D 1+'
The `~plasmapy.particles.particle_class.Particle.ionic_symbol`
attribute works for neutral atoms if charge information is available.
>>> deuterium = Particle("D", Z=0)
>>> deuterium.ionic_symbol
'D 0+'
If the particle doesn't belong to one of those categories, then
these attributes are `None`.
>>> positron.element is None
True
The attributes of a |Particle| instance may be used to test whether
or not a particle is an element, isotope, or ion.
>>> True if positron.element else False
False
>>> True if deuterium.isotope else False
True
>>> True if Particle('alpha').is_ion else False
True
Many of the attributes provide physical properties of a particle.
>>> electron.charge_number
-1
>>> proton.spin
0.5
>>> alpha.atomic_number
2
>>> deuteron.mass_number
2
>>> deuteron.binding_energy.to('MeV')
<Quantity 2.224... MeV>
>>> alpha.charge
<Quantity 3.20435...e-19 C>
>>> neutron.half_life
<Quantity 881.5 s>
>>> Particle('C-14').half_life.to(u.year)
<Quantity 5730. yr>
>>> deuteron.electron_number
0
>>> alpha.neutron_number
2
If a |Particle| instance represents an elementary particle, then
the unary ``~`` (invert) operator may be used to return the
particle's antiparticle.
>>> ~positron
Particle("e-")
A |Particle| instance may be used as the first argument to
|Particle|.
>>> iron = Particle('Fe')
>>> iron == Particle(iron)
True
>>> Particle(iron, mass_numb=56, Z=6)
Particle("Fe-56 6+")
If the previously constructed |Particle| instance represents an
element, then the ``Z`` and ``mass_numb`` arguments may be used to
specify an ion or isotope.
>>> iron = Particle('Fe')
>>> Particle(iron, Z=1)
Particle("Fe 1+")
>>> Particle(iron, mass_numb=56)
Particle("Fe-56")
Adding particles together will create a
`~plasmapy.particles.particle_collections.ParticleList`, which is
a list-like collection of particles.
>>> proton + 2 * electron
ParticleList(['p+', 'e-', 'e-'])
The ``>`` operator can be used with |Particle| and/or
`~plasmapy.particles.particle_collections.ParticleList` objects to
return the nuclear reaction energy.
>>> deuteron + triton > alpha + neutron
<Quantity 2.81810898e-12 J>
The `~plasmapy.particles.particle_class.Particle.categories` attribute
and `~plasmapy.particles.particle_class.Particle.is_category` method
may be used to find and test particle membership in categories.
Please refer to
`~plasmapy.particles.particle_class.Particle.is_category` for more
details, including a list of all valid particle categories.
"""
def __init__(
self,
argument: ParticleLike,
*_,
mass_numb: Optional[Integral] = None,
Z: Optional[Integral] = None,
):
# TODO: Remove the following block during or after the 0.9.0 release
if _:
raise TypeError(
"The parameters mass_numb and Z to Particle are now "
"keyword-only [e.g., Particle('H', mass_numb=2, Z=1)]."
)
# If argument is a Particle instance, then construct a new
# Particle instance for the same particle.
if isinstance(argument, Particle):
argument = argument.symbol
self.__inputs = argument, mass_numb, Z
self._initialize_attributes_and_categories()
self._store_particle_identity()
self._assign_particle_attributes()
self._add_charge_information()
self._add_half_life_information()
# If __name__ is not defined here, then problems with the doc
# build arise related to the Particle instances that are
# defined in plasmapy/particles/__init__.py.
self.__name__ = self.__repr__()
def _initialize_attributes_and_categories(self) -> NoReturn:
"""Create empty collections for attributes and categories."""
self._attributes = defaultdict(type(None))
self._categories = set()
def _validate_inputs(self) -> NoReturn:
"""Raise appropriate exceptions when inputs are invalid."""
argument, mass_numb, Z = self.__inputs
if not isinstance(argument, (Integral, np.integer, str, Particle)):
raise TypeError(
"The first positional argument when creating a "
"Particle object must be either an integer, string, or "
"another Particle object."
)
if mass_numb is not None and not isinstance(mass_numb, Integral):
raise TypeError("mass_numb is not an integer")
if Z is not None and not isinstance(Z, Integral):
raise TypeError("Z is not an integer.")
def _store_particle_identity(self) -> NoReturn:
"""Store the particle's symbol and identifying information."""
self._validate_inputs()
argument, mass_numb, Z = self.__inputs
symbol = _parsing.dealias_particle_aliases(argument)
if symbol in _special_particles.data_about_special_particles:
self._attributes["symbol"] = symbol
else:
self._store_identity_of_atom(argument)
def _store_identity_of_atom(self, argument) -> NoReturn:
"""
Store the particle's symbol, element, isotope, ion, mass number,
and charge number.
"""
_, mass_numb, Z = self.__inputs
try:
information_about_atom = _parsing.parse_and_check_atomic_input(
argument,
mass_numb=mass_numb,
Z=Z,
)
except InvalidParticleError as exc:
errmsg = _parsing.invalid_particle_errmsg(
argument, mass_numb=mass_numb, Z=Z
)
raise InvalidParticleError(errmsg) from exc
self._attributes["symbol"] = information_about_atom["symbol"]
for key in information_about_atom:
self._attributes[key] = information_about_atom[key]
def _assign_particle_attributes(self) -> NoReturn:
"""Assign particle attributes and categories."""
if self.symbol in _special_particles.data_about_special_particles:
self._assign_special_particle_attributes()
else:
self._assign_atom_attributes()
def _assign_special_particle_attributes(self) -> NoReturn:
"""Initialize special particles."""
attributes = self._attributes
categories = self._categories
for attribute in _special_particles.data_about_special_particles[self.symbol]:
attributes[attribute] = _special_particles.data_about_special_particles[
self.symbol
][attribute]
particle_taxonomy = (
_special_particles.particle_zoo._taxonomy_dict # noqa: SLF001
)
all_categories = particle_taxonomy.keys()
for category in all_categories:
if self.symbol in particle_taxonomy[category]:
categories.add(category)
if attributes["name"] in _specific_particle_categories:
categories.add(attributes["name"])
# Protons are treated specially because they can be considered
# both as special particles and atomic particles.
if self.symbol == "p+":
categories.update({"element", "isotope", "ion"})
argument, mass_numb, Z = self.__inputs
if mass_numb is None and Z is None:
return
if self.symbol != "p+":
raise InvalidParticleError(
"The keywords 'mass_numb' and 'Z' cannot be used when "
"creating Particle objects for special particles. To "
f"create a Particle object for {attributes['name']}s, "
f"use: Particle({attributes['particle']!r})"
)
if mass_numb not in (1, None) or Z not in (1, None):
raise InvalidParticleError(
"Cannot create a Particle representing a proton for a "
"mass number or charge number not equal to 1."
)
def _assign_atom_attributes(self) -> NoReturn:
"""Assign attributes and categories to elements, isotopes, and ions."""
attributes = self._attributes
categories = self._categories
element = attributes["element"]
isotope = attributes["isotope"]
ion = attributes["ion"]
if element:
categories.add("element")
if isotope:
categories.add("isotope")
if self.element and self._attributes["charge number"]:
categories.add("ion")
# Element properties
this_element = _elements.data_about_elements[element]
attributes["atomic number"] = this_element["atomic number"]
attributes["element name"] = this_element["element name"]
# Set the lepton number to zero for elements, isotopes, and
# ions. The lepton number will probably come up primarily
# during nuclear reactions.
attributes["lepton number"] = 0
if isotope:
this_isotope = _isotopes.data_about_isotopes[isotope]
attributes["baryon number"] = this_isotope["mass number"]
attributes["isotope mass"] = this_isotope.get("mass")
attributes["isotopic abundance"] = this_isotope.get("abundance", 0.0)
if this_isotope["stable"]:
attributes["half-life"] = np.inf * u.s
else:
attributes["half-life"] = this_isotope.get("half-life")
if element and not isotope:
attributes["standard atomic weight"] = this_element.get("atomic mass")
if ion in _special_particles.special_ion_masses:
attributes["mass"] = _special_particles.special_ion_masses[ion]
attributes["periodic table"] = _elements.PeriodicTable(
group=this_element["group"],
period=this_element["period"],
block=this_element["block"],
category=this_element["category"],
)
categories.add(this_element["category"])
def _add_charge_information(self) -> NoReturn:
"""Assign attributes and categories related to charge information."""
if self._attributes["charge number"] == 1:
self._attributes["charge"] = const.e.si
elif self._attributes["charge number"] is not None:
self._attributes["charge"] = self._attributes["charge number"] * const.e.si
if self._attributes["charge number"]:
self._categories.add("charged")
elif self._attributes["charge number"] == 0:
self._categories.add("uncharged")
def _add_half_life_information(self) -> NoReturn:
"""Assign categories related to stability."""
if self._attributes["half-life"] is not None:
if isinstance(self._attributes["half-life"], str):
self._categories.add("unstable")
elif self._attributes["half-life"] == np.inf * u.s:
self._categories.add("stable")
else:
self._categories.add("unstable")
def __repr__(self) -> str:
"""
Return a call string that would recreate this object.
Examples
--------
>>> lead = Particle('lead')
>>> repr(lead)
'Particle("Pb")'
"""
return f'Particle("{self.symbol}")'
def __str__(self) -> str:
"""Return the particle's symbol."""
return self.symbol
def __eq__(self, other) -> bool:
"""
Determine if two objects correspond to the same particle.
This method will return `True` if ``other`` is an identical
|Particle| instance or a `str` representing the same particle,
and return `False` if ``other`` is a different |Particle|, a
`str` representing a different particle or another type.
Examples
--------
>>> electron = Particle('e-')
>>> positron = Particle('e+')
>>> electron == positron
False
>>> electron == 'e-'
True
"""
if isinstance(other, str):
try:
other_particle = Particle(other)
except InvalidParticleError:
return False
else:
return self.symbol == other_particle.symbol
if not isinstance(other, self.__class__):
return NotImplemented
no_symbol_attr = "symbol" not in dir(self) or "symbol" not in dir(other)
no_attributes_attr = "_attributes" not in dir(self) or "_attributes" not in dir(
other
)
if no_symbol_attr or no_attributes_attr:
return False
same_particle = self.symbol == other.symbol
# The following two loops are a hack to enable comparisons
# between defaultdicts. By accessing all of the defined keys in
# each of the defaultdicts, this makes sure that
# self._attributes and other._attributes have the same keys.
# TODO: create function in utils to account for equality between
# defaultdicts, and implement it here
for attribute in self._attributes:
other._attributes[attribute]
for attribute in other._attributes:
self._attributes[attribute]
same_attributes = self._attributes == other._attributes
if same_particle and not same_attributes:
raise ParticleError(
f"{self} and {other} should be the same Particle, but "
f"have differing attributes.\n\n"
f"The attributes of {self} are:\n\n{self._attributes}\n\n"
f"The attributes of {other} are:\n\n{other._attributes}\n"
)
return same_particle
def __hash__(self) -> int:
"""
Allow use of `hash` so that a |Particle| instance may be used
as a key in a `dict`.
"""
return hash(self.__repr__())
def __invert__(self) -> Particle:
"""
Return the corresponding antiparticle, or raise an
`~plasmapy.particles.exceptions.ParticleError` if the particle
is not an elementary particle.
"""
return self.antiparticle
@property
def json_dict(self) -> dict:
"""
A JSON friendly dictionary representation of the particle.
See `AbstractParticle.json_dict` for more details.
Examples
--------
>>> lead = Particle('lead')
>>> lead.json_dict
{'plasmapy_particle': {'type': 'Particle',
'module': 'plasmapy.particles.particle_class',
'date_created': '...',
'__init__': {'args': ('Pb',), 'kwargs': {}}}}
>>> electron = Particle('e-')
>>> electron.json_dict
{'plasmapy_particle': {'type': 'Particle',
'module': 'plasmapy.particles.particle_class',
'date_created': '...',
'__init__': {'args': ('e-',), 'kwargs': {}}}}
"""
particle_dictionary = super().json_dict
particle_dictionary["plasmapy_particle"]["__init__"]["args"] = (self.symbol,)
return particle_dictionary
@property
def symbol(self) -> str:
"""
The symbol of the particle, atom, isotope, or ion.
This attribute will return the canonical symbol for special
particles (e.g., ``"p+"``, ``"e-"``, or ``"n"``), the atomic
symbol for elements (e.g., ``"Fe"``), the isotopic symbol for
isotopes (e.g., ``"D"`` or ``"Fe-56"``), and the ionic symbol
for ions (e.g., ``"N 1+"`` or ``"He-4 1+"``).
Examples
--------
>>> electron = Particle('positron')
>>> electron.symbol
'e+'
>>> deuteron = Particle('D 1+')
>>> deuteron.symbol
'D 1+'
"""
return self._attributes["symbol"]
@property
def antiparticle(self) -> Particle:
"""
The antiparticle corresponding to the particle.
This attribute may be accessed by using the unary operator ``~``
on a |Particle| instance.
Raises
------
`~plasmapy.particles.exceptions.ParticleError`
If the particle is not an elementary particle and does not
have a defined antiparticle.
Examples
--------
>>> electron = Particle('e-')
>>> electron.antiparticle
Particle("e+")
>>> antineutron = Particle('antineutron')
>>> ~antineutron
Particle("n")
"""
if self.symbol in _special_particles.antiparticles:
return Particle(_special_particles.antiparticles[self.symbol])
else:
raise ParticleError(
"The unary operator can only be used for elementary "
"particles and antiparticles."
)
@property
def element(self) -> Optional[str]:
"""
The atomic symbol if the particle corresponds to an element, and
`None` otherwise.
Examples
--------
>>> alpha = Particle('alpha')
>>> alpha.element
'He'
"""
return self._attributes["element"]
@property
def isotope(self) -> Optional[str]:
"""
The isotope symbol if the particle corresponds to an isotope,
and `None` otherwise.
Examples
--------
>>> alpha = Particle('alpha')
>>> alpha.isotope