Completed
Push — master ( a40a09...daea06 )
by Ben
01:00
created

_get()   A

Complexity

Conditions 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
c 0
b 0
f 0
dl 0
loc 7
rs 9.4285
1
"Some utility methods"
2
import numpy as np
3
from numpy import cos
4
from numpy import pi
5
from numpy import sin
6
7
8
def lzproperty(attribute):
9
    """
10
    Lazy property: evaluate property only once
11
    """
12
    save_att = '_' + attribute.__name__
13
14
    @property
15
    def _get(self):
16
        try:
17
            return getattr(self, save_att)
18
        except AttributeError:
19
            setattr(self, save_att, attribute(self))
20
        return getattr(self, save_att)
21
    return _get
22
23
24
class ClassOperation(object):
25
    """
26
    Define arithmetic operation on Class
27
    """
28
    def __add__(self, other):
29
        return ClassOperationResult('__add__', self, other)
30
31
    def __sub__(self, other):
32
        return ClassOperationResult('__sub__', self, other)
33
34
    def __mul__(self, other):
35
        return ClassOperationResult('__mul__', self, other)
36
37
    def __gt__(self, other):
38
        return ClassOperationResult('__gt__', self, other)
39
40
41
class ClassOperationResult(ClassOperation):
42
    """
43
    Result of Class Operation
44
    """
45
    def __init__(self, operation, cls1, cls2):
46
        """
47
        """
48
        self.cls1 = cls1
49
        self.cls2 = cls2
50
        self._operation = operation
51
52
    def __getattr__(self, attr):
53
        attr1 = getattr(self.cls1, attr)
54
        attr2 = getattr(self.cls2, attr)
55
56
        try:
57
            return getattr(attr1, self._operation)(attr2)
58
59
        except AttributeError:
60
            return (lambda *args, **kwargs:
61
                    getattr(attr1(*args), self._operation)(attr2(*args)))
62
63
64
def rotation(theta, axis=-1):
65
    """
66
    Return a rotation matrix around axis
67
    0:x, 1:y, 2:z
68
    """
69
    ct = cos(theta)
70
    st = sin(theta)
71
72
    if axis in (0, -3):
73
        return np.array([[1, 0, 0],
74
                         [0, ct, st],
75
                         [0, -st, ct]])
76
77
    if axis in (1, -2):
78
        return np.array([[ct, 0, st],
79
                         [0, 1, 0],
80
                         [-st, 0, ct]])
81
82
    if axis in (2, -1):
83
        return np.array([[ct, st, 0],
84
                         [-st, ct, 0],
85
                         [0, 0, 1]])
86
87
88
def galactic_to_galactocentric(l, b, distance, rsun):
89
    slc = sin(l/180*pi)
90
    clc = cos(l/180*pi)
91
    sbc = sin(b/180*pi)
92
    cbc = cos(b/180*pi)
93
    rgalc = distance*cbc
94
    xc = rgalc*slc
95
    yc = rsun-rgalc*clc
96
    zc = distance*sbc
97
    return np.array([xc, yc, zc])
98