nifty_los_implementation.pyx 6.15 KB
Newer Older
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
# -*- coding: utf-8 -*-

import numpy as np
cimport numpy as np
cimport cython


class los_integrator(object):
    def __init__(self, shape, start, end):
        self.dtype = np.dtype('float')

        self.shape = tuple(shape)
        self.start = np.array(start, dtype=self.dtype)
        self.end = np.array(end, dtype=self.dtype)

        assert(np.all(np.array(self.shape) != 0))
        assert(len(self.shape) == len(self.start) == len(self.end))
        assert(len(self.start.shape) == len(self.end.shape) == 1)

    def integrate(self):
        if np.all(self.start == self.end):
            return self._empty_results()
        try:
            projected_start = self._project_to_cuboid(mode='start')
            projected_end = self._project_to_cuboid(mode='end')
        except ValueError:
            return self._empty_results()

        (indices, weights) = self._integrate_through_cuboid(projected_start,
                                                            projected_end)
        return (indices, weights)

    def _empty_results(self):
        return ([np.array([], dtype=np.dtype('int'))] * len(self.shape),
                np.array([], dtype=np.dtype('float')))

    def _project_to_cuboid(self, mode):
        if mode == 'start':
            a = self.start
            b = self.end
        elif mode == 'end':
            a = self.end
            b = self.start
        else:
            raise ValueError

        if np.all(np.zeros_like(a) <= a) and np.all(a <= np.array(self.shape)):
            return a

        c = b - a

        surface_list = []
        for i in xrange(len(self.shape)):
            surface_list += [[i, 0]]
            surface_list += [[i, self.shape[i]]]

        translator_list = map(lambda z:
                              self._get_translator_to_surface(a, c, *z),
                              surface_list)
        # sort the translators according to their norm, save the sorted indices
        translator_index_list = np.argsort(map(np.linalg.norm,
                                               translator_list))
        # iterate through the indices -from short to long translators- and
        # take the first translator which brings a to the actual surface of
        # the cuboid and not just to one of the parallel planes
        found = False
        for i in translator_index_list:
            p = a + translator_list[i]
            if np.all(np.zeros_like(p) <= p) and \
                    np.all(p <= np.array(self.shape)):
                found = True
                break

        if not found:
            raise ValueError(
                "ERROR: Line-of-sight does not go through cuboid.")

        return p

    def _get_translator_to_surface(self, point, full_direction,
                                   dimension_index, surface):
        """
        translates 'point' along the vector 'direction' such that the
        dimension with index 'dimension_index' has the value 'surface'
        """
        direction_scaler = np.divide((surface - point[dimension_index]),
                                     full_direction[dimension_index])
        if direction_scaler < 0 or direction_scaler > 1:
            return point * np.nan

        scaled_direction = full_direction * direction_scaler
        return scaled_direction

    def _integrate_through_cuboid(self, start, end):
        # estimate the maximum number of cells that could be hit
        # the current estimator is: norm of the vector times number of dims
        num_estimate = np.ceil(np.linalg.norm(end - start))*len(start)

        index_list = np.empty((num_estimate, len(start)),
                              dtype=np.dtype('int'))
        weight_list = np.empty((num_estimate), self.dtype)

        current_position = start
        i = 0
        while True:
            next_position, weight = self._get_next_position(current_position,
                                                            end)
            floor_current_position = np.floor(current_position)
            index_list[i] = floor_current_position
            weight_list[i] = weight

            if np.all(np.floor(current_position) == np.floor(end)):
                break

            current_position = next_position
            i += 1

        return list(index_list[:i].T), weight_list[:i]

    def _get_next_position(self, position, end_position):
        full_direction = end_position - position

        surface_list = []
        for i in xrange(len(position)):
            surface_list += [[i, strong_floor(position[i])]]
            surface_list += [[i, strong_ceil(position[i])]]

        translator_list = map(lambda z: self._get_translator_to_surface(
                                                              position,
                                                              full_direction,
                                                              *z),
                              surface_list)

#        index_of_best_translator = np.argsort(np.linalg.norm(translator_list,
#                                                             axis=1))[0]
        translator_list = np.array(translator_list)
        index_of_best_translator = np.linalg.norm(translator_list, axis=1)
        index_of_best_translator = np.argsort(index_of_best_translator)[0]


        best_translator = translator_list[index_of_best_translator]
        # if the surounding surfaces are not reachable, it must be the case
        # that the current position is in the same cell as the endpoint
        if np.isnan(np.linalg.norm(best_translator)):
            floor_position = np.floor(position)
            # check if position is in the same cell as the endpoint
            assert(np.all(floor_position == np.floor(end_position)))
            weight = np.linalg.norm(end_position - position)
            next_position = None
        else:
            next_position = position + best_translator
            weight = np.linalg.norm(best_translator)
        return (next_position, weight)


def strong_floor(x):
    floor_x = np.floor(x)
    if floor_x == x:
        return floor_x-1
    else:
        return floor_x


def strong_ceil(x):
    ceil_x = np.ceil(x)
    if ceil_x == x:
        return ceil_x+1
    else:
        return ceil_x