forked from oliverkn/ntuplizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlorentz_vector.py
1081 lines (887 loc) · 33.2 KB
/
lorentz_vector.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
# Licensed under a 3-clause BSD style license, see LICENSE.
"""
Vector classes
==============
Two vector classes are available:
* ``Vector3D`` : a 3-dimensional vector.
* ``LorentzVector``: a Lorentz vector, i.e. a 4-dimensional Minkowski space-time vector
or a 4-momentum vector.
The metric is (-1,-1,-1,+1).
"""
# -----------------------------------------------------------------------------
# Import statements
# -----------------------------------------------------------------------------
from __future__ import absolute_import
# from skhep.utils.py23 import *
# from skhep.utils.exceptions import *
from math import sqrt, atan2, cos, sin, acos, degrees, log, pi, sinh
# -----------------------------------------------------------------------------
# Vector class in 3D
# -----------------------------------------------------------------------------
class Vector3D(object):
"""
Vector class in 3 dimensions.
Constructors:
__init__(x=0., y=0., z=0.)
origin()
frompoint(x, y, z)
fromvector(avector)
fromsphericalcoords(r, theta, phi)
fromcylindricalcoords(rho, phi, z)
fromiterable(values)
"""
def __init__(self, x=0., y=0., z=0.):
"""Default constructor.
Examples
--------
>>> v1 = Vector3D()
>>> v1
<Vector3D (x=0.0,y=0.0,z=0.0)>
>>> v2 = Vector3D(1,2,3)
>>> v2
<Vector3D (x=1,y=2,z=3)>
"""
self.__values = [x, y, z]
@classmethod
def origin(cls):
"""Shortcut constuctor for the origin (x=0.,y=0.,z=0.).
Equivalent to the default constructor Vector3D().
"""
return cls(0., 0., 0.)
@classmethod
def frompoint(cls, x, y, z):
"""Constructor from an explicit space point."""
return cls(x, y, z)
@classmethod
def fromvector(cls, other):
"""Copy constructor."""
return cls(other.x, other.y, other.z)
@classmethod
def fromsphericalcoords(cls, r, theta, phi):
"""Constructor from a space point specified in spherical coordinates.
Parameters
----------
r : radius, the radial distance from the origin (r > 0)
theta : inclination in radians (theta in [0, pi] rad)
phi : azimuthal angle in radians (phi in [0, 2pi) rad)
"""
x = r * sin(theta) * cos(phi)
y = r * sin(theta) * sin(phi)
z = r * cos(theta)
return cls(x, y, z)
@classmethod
def fromcylindricalcoords(cls, rho, phi, z):
"""Constructor from a space point specified in cylindrical coordinates.
Parameters
----------
rho : radial distance from the z-axis (rho > 0)
phi : azimuthal angle in radians (phi in [-pi, pi) rad)
z : height
"""
x = rho * cos(phi)
y = rho * sin(phi)
z = z
return cls(x, y, z)
@classmethod
def fromiterable(cls, values):
"""Constructor from a suitable iterable object.
Suitable means here that all entries are numbers
and the length equals 3.
"""
values = list(values)
if not len(values)==3:
raise ValueError( 'Input iterable length = {0}! Please check your inputs.'.format(len(values)) )
for i, v in enumerate(values):
if not isinstance( v, (int,float) ):
raise ValueError( 'Component #{0} is not a number!'.format(i) )
return cls(values[0], values[1], values[2])
@property
def x(self):
"""Return the x, aka first coordinate at position 0."""
return self.__values[0]
@x.setter
def x(self, value):
"""Sets x, aka first coordinate at position 0."""
self.__values[0] = value
@property
def y(self):
"""Return the y, aka second coordinate at position 1."""
return self.__values[1]
@y.setter
def y(self, value):
"""Sets y, aka second coordinate at position 1."""
self.__values[1] = value
@property
def z(self):
"""Return the z, aka third coordinate at position 2."""
return self.__values[2]
@z.setter
def z(self, value):
"""Sets z, aka third coordinate at position 2."""
self.__values[2] = value
@property
def rho(self):
"""Return the cylindrical coordinate rho."""
return sqrt(self.x**2 + self.y**2)
@property
def r(self):
"""Return the spherical coordinate r."""
return self.mag
def costheta(self):
"""Return the cosine of the spherical coordinate theta."""
if self.mag == 0.:
return 1.
else:
return self.z / self.mag
def theta(self, deg=False):
"""Return the spherical coordinate theta.
Parameters
----------
deg : float, optional
Return the angle in degrees (default is radians).
"""
theta = acos(self.costheta())
return theta if not deg else degrees(theta)
def phi(self, deg=False):
"""Return the spherical or cylindrical coordinate phi.
Parameters
----------
deg : float, optional
Return the angle in degrees (default is radians).
"""
phi = atan2(self.y, self.x)
return phi if not deg else degrees(phi)
def set(self, x, y, z):
"""Update the vector components all at once."""
self.__values = [x, y, z]
def __setitem__(self, i, value):
"""Update/set the ith vector component (commencing at 0, of course)."""
try:
self.__values[i] = value
except IndexError:
raise IndexError(
'Vector3D is of length {0} only!'.format(len(self)))
def __getitem__(self, i):
"""Get the ith vector component (commencing at 0, of course)."""
try:
return self.__values[i]
except IndexError:
raise IndexError( 'Vector3D is of length {0} only!'.format(len(self)))
def tolist(self):
"""Return the vector as a list."""
return list(self.__values)
def __len__(self):
"""Length of the vector, i.e. the number of elements = 3."""
return len(self.__values)
@property
def mag(self):
"""Magnitude, a.k.a. norm, of the vector."""
return sqrt(self.mag2)
@property
def mag2(self):
"""Square of the magnitude, a.k.a. norm, of the vector."""
return sum(v ** 2 for v in self.__values)
def __abs__ ( self ) :
"""Get the absolute value for the vector.
Example
-------
>>> v = ...
>>> a = abs(v)
"""
return self.mag
def copy(self) :
"""Get a copy of the vector.
Example
-------
>>> v = ...
>>> v1 = v.copy()
"""
return Vector3D( self[0] , self[1] , self[2] )
def unit(self):
"""Return the normalized vector, i.e. the unit vector along the direction of itself."""
mag = self.mag
if mag > 0. and mag != 1. :
return Vector3D.fromiterable([v / mag for v in self.__values])
else:
return self
def __iadd__(self, other):
"""(self)Addition with another vector, i.e. self+other.
Example
-------
>>> v1 = ...
>>> v2 = ...
>>> v1 += v2
"""
if not isinstance ( other , Vector3D ) :
raise Exception("invalid operation '+=' between a 'Vector3D' and a '{0}'".format(other.__class__.__name__))
self.__values[0] += other.__values[0]
self.__values[1] += other.__values[1]
self.__values[2] += other.__values[2]
return self
def __isub__(self, other):
"""(self)Subtraction with another vector, i.e. self+other.
Example
-------
>>> v1 = ...
>>> v2 = ...
>>> v1 -= v2
"""
if not isinstance ( other , Vector3D ) :
raise Exception("invalid operation '-=' between a 'Vector3D' and a '{0}'".format(other.__class__.__name__))
self.__values[0] -= other.__values[0]
self.__values[1] -= other.__values[1]
self.__values[2] -= other.__values[2]
return self
def __add__(self, other):
"""Addition with another vector, i.e. self+other."""
if not isinstance ( other , Vector3D ) : return NotImplemented
v = self.copy()
v+= other
return v
def __sub__(self, other):
"""Subtraction with another vector, i.e. self-other."""
if not isinstance ( other , Vector3D ) : return NotImplemented
v = self.copy()
v-= other
return v
def __imul__(self, other):
"""Scaling of the vector by a number.
Example
-------
>>> v = ...
>>> v *= 2
"""
if isinstance ( other , ( int , float ) ) :
return Vector3D.fromiterable ( [v * other for v in self.__values ] )
else:
raise Exception("invalid operation '*=' between a 'Vector3D' and a '{0}'".format(other.__class__.__name__))
def __itruediv__(self, number):
"""Scaling of the vector by a number.
Example
-------
>>> v = ...
>>> v /= 2
"""
if not isinstance ( number , ( int , float ) ) :
raise Exception("invalid operation '/=' between a 'Vector3D' and a '{0}'".format(number.__class__.__name__))
elif 0 == number : raise ZeroDivisionError
self *= ( 1.0/number )
return self
__idiv__ = __itruediv__
def __mul__(self, other):
"""Multiplication of the vector by either another vector or a number.
Multiplication of two vectors is equivalent to the dot product, see dot(...).
Example
-------
>>> v2 = v1 * 2
>>> number = v1 * v3
"""
if isinstance ( other , Vector3D ) :
return self.dot(other)
v = self.copy()
v *= other
return v
def __rmul__(self, other):
"""Right multiplication of the vector by either another vector or a number."""
return self.__mul__(other)
def __truediv__(self, number):
"""Division of the vector by a number."""
v = self.copy()
v /= number
return v
__div__ = __truediv__
def __eq__ ( self , other ) :
"""Equality to another vector, or, equality to zero.
Example
-------
>>> v1 = ...
>>> v2 = ...
>>> print v1 == v2
>>> print v1 == 0
"""
from skhep.math.numeric import isequal
## comparsion with scalar zero, very useful in practice
if isinstance ( other , ( float , int , int ) ) and isequal ( other , 0 ) :
return isequal ( self[0] , 0 ) and isequal ( self[1] , 0 ) and isequal ( self[2] , 0 )
elif not isinstance ( other , Vector3D) :
return NotImplemented
##
return isequal ( self[0] , other[0] ) and isequal ( self[1] , other[1] ) and isequal ( self[2] , other[2] )
def __ne__ (self, other) :
"""Non-equality to another vector.
Example
-------
>>> v1 = ...
>>> v2 = ...
>>> print v1 != v2
"""
return not ( self == other )
def __nonzero__ ( self ) :
"""Non-zero vector?
Example
-------
>>> vct = ...
>>> if vct : ...
"""
return 0 != self.mag2
__bool__ = __nonzero__
def __iter__(self):
"""Iterator implementation for the vector components."""
return self.__values.__iter__()
def dot(self, other):
"""Dot product with another vector."""
return sum(v1 * v2 for v1, v2 in zip(self.__values, other.__values))
def cross(self, other ):
"""Cross product with another vector."""
return Vector3D( self[1] * other[2] - self[2] * other[1],
self[2] * other[0] - self[0] * other[2],
self[0] * other[1] - self[1] * other[0]
)
def rotate(self, angle, *args):
"""Rotate vector by a given angle (in radians) around a given axis."""
if len(args) == 1 and isinstance(args[0], Vector3D):
ux, uy, uz = args[0].__values
elif len(args) == 1 and len(args[0]) == 3:
ux, uy, uz = args[0]
elif len(args) == 3:
ux, uy, uz = args
else:
raise TypeError('Input object not a Vector3D nor an iterable with 3 elements.')
for i, u in enumerate((ux, uy, uz)):
if not isinstance( u, (int,float) ):
raise ValueError( 'Component #{0} is not a number!'.format(i) )
norm = sqrt(ux**2 + uy**2 + uz**2)
if norm != 1.0:
ux = ux / norm; uy = uy / norm; uz = uz / norm;
c, s = cos(angle), sin(angle)
c1 = 1. - c
xp = (c + ux**2 * c1) * self.x + (ux * uy * c1 - uz * s) * self.y \
+ (ux * uz * c1 + uy * s) * self.z
yp = (ux * uy * c1 + uz * s) * self.x + (c + uy**2 * c1) * self.y \
+ (uy * uz * c1 - ux * s) * self.z
zp = (ux * uz * c1 - uy * s) * self.x + (uy * uz * c1 + ux * s) * self.y \
+ (c + uz**2 * c1) * self.z
return Vector3D(xp, yp, zp)
def rotatex(self, angle):
"""Rotate vector by a given angle (in radians) around the x axis."""
return self.rotate(angle, 1, 0, 0)
def rotatey(self, angle):
"""Rotate vector by a given angle (in radians) around the y axis."""
return self.rotate(angle, 0, 1, 0)
def rotatez(self, angle):
"""Rotate vector by a given angle (in radians) around the z axis."""
return self.rotate(angle, 0, 0, 1)
def cosdelta ( self , other ) :
"""Get cos(angle) with respect to another vector
"""
m1 = self.mag2
if 0 >= m1 : return 1.0
m2 = other.mag2
if 0 >= m2 : return 1.0
r = self.dot( other ) / sqrt ( m1 * m2 )
return max ( -1.0 , min ( 1.0 , r ) )
def angle(self, other, deg=False):
"""
Angle with respect to another vector.
Parameters
----------
deg : float, optional
Return the angle in degrees (default is radians).
"""
cd = self.cosdelta ( other )
return acos(cd) if not deg else degrees(acos(cd))
def isparallel(self, other):
"""Check if another vector is parallel.
Two vectors are parallel if they have the same direction but not necessarily the same magnitude.
"""
from skhep.math.numeric import isequal
return isequal ( self.cosdelta(other) , 1 )
def isantiparallel(self, other):
"""Check if another vector is antiparallel.
Two vectors are antiparallel if they have opposite direction but not necessarily the same magnitude.
"""
from skhep.math.numeric import isequal
return isequal ( self.cosdelta(other) , -1 )
def iscollinear ( self , other ) :
"""Check if another vector is collinear
Two vectors are collinear if they have parallel or antiparallel
"""
from skhep.math.numeric import isequal
return isequal ( abs ( self.cosdelta ( other ) ) , 1 )
def isopposite ( self , other):
"""Two vectors are opposite if they have the same magnitude but opposite direction."""
from skhep.math.numeric import isequal
added = self + other
return added == 0
def isperpendicular(self, other):
"""Check if another vector is perpendicular."""
from skhep.math.numeric import isequal
return isequal ( self.dot ( other ) , 0 , scale = max( self.mag2 , other.mag2 ) )
def __repr__(self):
"""Class representation."""
return "<Vector3D (x={0},y={1},z={2})>".format(*self.__values)
def __str__(self):
"""Simple class representation."""
return str(tuple(self.__values))
#-----------------------------------------------------------------------------
# Lorentz vector class
#-----------------------------------------------------------------------------
class LorentzVector(object):
"""
Class representing a Lorentz vector,
either a 4-dimensional Minkowski space-time vector or a 4-momentum vector.
The 4-vector components can be seen as (x,y,z,t) or (px,py,pz,E).
Constructors:
__init__(x=0., y=0., z=0., t=0.)
from4vector(avector)
from3vector(vector3d, t)
"""
def __init__(self, x=0., y=0., z=0., t=0.):
"""Default constructor.
Example
-------
>>> v1 = LorentzVector()
>>> v1
"""
self.__vector3d = Vector3D(x, y, z)
self.__t = t
@classmethod
def from4vector(cls, other):
"""Copy constructor."""
return cls(other.x, other.y, other.z, other.t)
@classmethod
def from3vector(cls, vector3d, t):
"""Constructor from a Vector3D and the time/energy component."""
return cls(vector3d.x, vector3d.y, vector3d.z, t)
@classmethod
def fromiterable(cls, values):
"""Constructor from a suitable iterable object.
Suitable means here that all entries are numbers
and the length equals 4.
"""
values = list(values)
if not len(values)==4:
raise ValueError( 'Input iterable length = {0}! Please check your inputs.'.format(len(values)) )
for i, v in enumerate(values):
if not isinstance( v, (int,float) ):
raise ValueError( 'Component #{0} is not a number!'.format(i) )
return cls(values[0], values[1], values[2], values[3])
@property
def x(self):
"""Return the coordinate x, aka first coordinate at position 0."""
return self.__vector3d.x
@x.setter
def x(self, value):
"""Sets x, aka first coordinate at position 0."""
self.__vector3d.x = value
@property
def y(self):
"""Return the coordinate x, aka second coordinate at position 1."""
return self.__vector3d.y
@y.setter
def y(self, value):
"""Sets y, aka second coordinate at position 1."""
self.__vector3d.y = value
@property
def z(self):
"""Return the coordinate z, aka third coordinate at position 2."""
return self.__vector3d.z
@z.setter
def z(self, value):
"""Sets z, aka third coordinate at position 2."""
self.__vector3d.z = value
@property
def vector(self):
"""Return a copy of the vector of spatial components."""
return self.__vector3d.copy()
@property
def t(self):
"""Return the time/energy component, aka coordinate at position 3."""
return self.__t
@t.setter
def t(self, value):
"""Sets t, aka coordinate at position 3."""
self.__t = value
def costheta(self):
"""Return the cosinus of the spherical coordinate theta."""
return self.__vector3d.costheta()
def theta(self, deg=False):
"""
Return the spherical coordinate theta.
Parameters
----------
deg : float, optional
Return the angle in degrees (default is radians).
"""
return self.__vector3d.theta(deg)
def phi(self, deg=False):
"""
Return the spherical or cylindrical coordinate phi.
Parameters
----------
deg : float, optional
Return the angle in degrees (default is radians).
"""
return self.__vector3d.phi(deg)
@property
def px(self):
"""Return the Vector3D coordinate px, aka first momentum coordinate at position 0."""
return self.__vector3d.x
@px.setter
def px(self, value):
"""Sets px, aka first momentum coordinate at position 0."""
self.__vector3d.x = value
@property
def py(self):
"""Return the Vector3D coordinate px, aka second momentum coordinate at position 1."""
return self.__vector3d.y
@py.setter
def py(self, value):
"""Sets py, aka second momentum coordinate at position 1."""
self.__vector3d.y = value
@property
def pz(self):
"""Return the Vector3D coordinate pz, aka third momentum coordinate at position 2."""
return self.__vector3d.z
@pz.setter
def pz(self, value):
"""Sets pz, aka third momentum coordinate at position 2."""
self.__vector3d.z = value
@property
def e(self):
"""Return the energy/time component, aka momentum coordinate at position 3."""
return self.__t
@e.setter
def e(self, value):
"""Sets e, aka momentum coordinate at position 3."""
self.__t = value
def set(self, x, y, z, t):
"""Update/set all components at once."""
self.__vector3d = Vector3D(x, y, z)
self.__t = t
def setpxpypzm(self, px, py, pz, m):
"""Set the px,py,pz components and the mass."""
self.__vector3d.x = px; self.__vector3d.y = py; self.__vector3d.z = pz
if m > 0.:
self.__t = sqrt(px**2 + py**2 + pz**2 + m**2)
else:
self.__t = sqrt(px**2 + py**2 + pz**2 - m**2)
def setpxpypze(self, px, py, pz, e):
"""Set the px,py,pz components and the energy."""
self.set(px,py,pz,e)
def setptetaphim(self, pt, eta, phi, m):
""" Set the transverse momentum, the pseudorapidity, the angle phi and the mass."""
px, py, pz = pt*cos(phi), pt*sin(phi), pt*sinh(eta)
self.setpxpypzm(px,py,pz,m)
def setptetaphie(self, pt, eta, phi, e):
""" Set the transverse momentum, the pseudorapidity, the angle phi and the energy."""
px, py, pz = pt*cos(phi), pt*sin(phi), pt*sinh(eta)
self.setpxpypze(px,py,pz,e)
def tolist(self):
"""Return the LorentzVector as a list."""
return list(self.__vector3d) + [self.__t]
def __setitem__(self, i, value):
"""Update/set the ith vector component (commencing at 0, of course)."""
try:
if i == 3: self.__t = value
else: self.__vector3d[i] = value
except IndexError:
raise IndexError(
'LorentzVector is of length {0} only!'.format(len(self)))
def __getitem__(self, i):
"""Get the ith vector component (commencing at 0, of course)."""
try:
return self.tolist()[i]
except IndexError:
raise IndexError( 'LorentzVector is of length {0} only!'.format(len(self)))
def __len__(self):
"""Length of the LorentzVector, i.e. the number of elements = 4."""
return len(self.tolist())
@property
def p(self):
"""Return the momentum, aka norm of the momentum vector."""
return self.__vector3d.mag
@property
def pt(self):
"""Return the transverse momentum, aka transverse component of the momentum vector."""
return self.perp
@property
def et(self):
"""Return the transverse energy."""
return self.e * ( self.pt / self.p )
@property
def m(self):
"""Return the invariant mass."""
return self.mag
@property
def m2(self):
"""Return the square of the invariant mass."""
return self.mag2
@property
def mass(self):
"""Return the invariant mass."""
return self.mag
@property
def mass2(self):
"""Return the square of the invariant mass."""
return self.mag2
@property
def mt(self):
"""Return the transverse mass."""
return self.transversemass
@property
def mt2(self):
"""Return the square of the transverse mass."""
return self.transversemass2
@property
def transversemass(self):
"""Return the transverse mass."""
mt2 = self.transversemass2
return sqrt(mt2) if mt2 >= 0. else -sqrt(-mt2)
@property
def transversemass2(self):
"""Return the square of the transverse mass."""
return self.e**2 - self.pz**2
@property
def beta(self):
"""Return :math:`\\beta = v/c`."""
return self.p / self.e
@property
def gamma(self):
"""Return :math:`\\gamma = 1/\\sqrt{1-\\beta^2}`."""
if self.beta < 1:
return 1. / sqrt(1. - self.beta**2)
else:
return 10E10
@property
def eta(self):
"""Return the pseudorapidity."""
if abs(self.costheta()) < 1.:
return -0.5 * log( (1. - self.costheta())/(1. + self.costheta()) )
else:
return 10E10 if self.z > 0 else -10E10
@property
def boostvector(self):
"""Return the spatial component divided by the time component."""
return Vector3D(self.x / self.t, self.y / self.t, self.z / self.t)
@property
def pseudorapidity(self):
""""Return the pseudorapidity. Alternative to eta() method."""
return self.eta
@property
def rapidity(self):
"""Return the rapidity."""
return 0.5 * log( (self.e + self.pz)/(self.e - self.pz) )
@property
def mag(self):
"""Magnitude, a.k.a. norm, of the Lorentz vector."""
mag2 = self.mag2
return sqrt(mag2) if mag2 >= 0. else -sqrt(-mag2)
@property
def mag2(self):
"""Square of the magnitude, a.k.a. norm, of the Lorentz vector."""
return self.t**2 - self.__vector3d.mag2
@property
def perp2(self):
"""Square of the transverse component, in the (x,y) plane, of the spatial components."""
return self.x**2 + self.y**2
@property
def perp(self):
"""Transverse component of the spatial components."""
return sqrt(self.perp2)
def copy(self) :
"""Get a copy of the LorentzVector.
Example
-------
>>> v = ...
>>> v1 = v.copy()
"""
return LorentzVector( self[0] , self[1] , self[2] , self[3] )
def __iadd__(self, other):
"""(self)Addition with another LorentzVector, i.e. self+other.
Example
-------
>>> v1 = ...
>>> v2 = ...
>>> v1 += v2
"""
if not isinstance ( other , LorentzVector ) :
raise Exception("invalid operation '+=' between a 'LorentzVector' and a '{0}'".format(other.__class__.__name__))
self.__vector3d += other.__vector3d
self.__t += other.__t
return self
def __isub__(self, other):
"""(self)Subtraction with another LorentzVector, i.e. self+other.
Example
-------
>>> v1 = ...
>>> v2 = ...
>>> v1 -= v2
"""
if not isinstance ( other , LorentzVector ) :
raise Exception("invalid operation '-=' between a 'LorentzVector' and a '{0}'".format(other.__class__.__name__))
self.__vector3d -= other.__vector3d
self.__t -= other.__t
return self
def __add__(self, other):
"""Addition with another LorentzVector, i.e. self+other."""
v = self.copy()
v+= other
return v
def __sub__(self, other):
"""Subtraction with another LorentzVector, i.e. self-other."""
v = self.copy()
v-= other
return v
def __imul__(self, other):
"""Scaling of the Lorentz vector with a number.
Example
-------
>>> v = ...
>>> v *= 2
"""
if isinstance ( other , ( int , float ) ) :
return LorentzVector.fromiterable ( [v * other for v in self.tolist() ] )
else:
raise Exception("invalid operation '*=' between a 'LorentzVector' and a '{0}'".format(other.__class__.__name__))
def __itruediv__(self, number):
"""Scaling of the Lorentz vector with a number.
Example
-------
>>> v = ...
>>> v /= 2
"""
if not isinstance ( number , ( int , float ) ) :
raise Exception("invalid operation '/=' between a 'LorentzVector' and a '{0}'".format(number.__class__.__name__))
elif 0 == number : raise ZeroDivisionError
self *= ( 1.0/number )
return self
__idiv__ = __itruediv__
def __mul__(self, other):
"""Multiplication of the LorentzVector by either another LorentzVector or a number.
Multiplication of two LorentzVector is equivalent to the dot product, see dot(...).
Example
-------
>>> v2 = v1 * 2
>>> number = v1 * v3
"""
if isinstance ( other , LorentzVector ):
return self.dot(other)
v = self.copy()
v *= other
return v
def __rmul__(self, other):
"""Right multiplication of the LorentzVector by either another LorentzVector or a number."""
return self.__mul__(other)
def __truediv__(self, number):
"""Division of the LorentzVector by a number."""
v = self.copy()
v /= number
return v
__div__ = __truediv__
def __eq__ ( self , other ) :
"""Equality to another LorentzVector, or, equality to zero.
Example
-------
>>> v1 = ...
>>> v2 = ...
>>> print v1 == v2
>>> print v1 == 0
"""
from skhep.math.numeric import isequal
## comparsion with scalar zero, very useful in practice
if isinstance ( other , ( float , int , int ) ) and isequal ( other , 0 ) :
return isequal ( self[0] , 0 ) and isequal ( self[1] , 0 ) and isequal ( self[2] , 0 ) \
and isequal ( self[3] , 0 )
elif not isinstance ( other , LorentzVector ) :
return NotImplemented
##
return isequal ( self[0] , other[0] ) and isequal ( self[1] , other[1] ) and isequal ( self[2] , other[2] ) \
and isequal ( self[3] , other[3] )
def __ne__ (self, other) :
"""Non-equality to another Lorentz vector.
Example
-------
>>> v1 = ...
>>> v2 = ...
>>> print v1 != v2
"""
return not ( self == other )
def __iter__(self):
"""Iterator implementation for the Lorentz vector components."""
return self.tolist().__iter__()
def boost(self, *args):
"""Apply a Lorentz boost on the Lorentz vector."""
if len(args) == 1 and isinstance(args[0], Vector3D):
bx, by, bz = args[0].x, args[0].y, args[0].z
elif len(args) == 1 and len(args[0]) == 3:
bx, by, bz = args[0]
elif len(args) == 3:
bx, by, bz = args
else:
raise TypeError('Input object not a Vector3D nor an iterable with 3 elements.')
for i, b in enumerate((bx, by, bz)):
if not isinstance( b, (int,float) ):