~ubuntu-branches/ubuntu/precise/python-chaco/precise

« back to all changes in this revision

Viewing changes to enthought/chaco/datamapper.py

  • Committer: Bazaar Package Importer
  • Author(s): Varun Hiremath
  • Date: 2008-12-29 02:34:05 UTC
  • Revision ID: james.westby@ubuntu.com-20081229023405-x7i4kp9mdxzmdnvu
Tags: upstream-3.0.1
ImportĀ upstreamĀ versionĀ 3.0.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
CAUTION: This is an old file from Chaco 1.x to support the spatial subdivision 
 
3
structures.  It will be refactored soon.
 
4
 
 
5
If you are looking for Chaco's mappers (subclasses of AbstractMapper),
 
6
look in abstract_mapper.py, linear_mapper.py, and log_mapper.py.
 
7
 
 
8
Defines AbstractDataMapper and BruteForceDataMapper classes, and related trait
 
9
and functions.
 
10
"""
 
11
 
 
12
 
 
13
from sets import Set
 
14
 
 
15
from numpy import array, concatenate, take, argsort, argmin, \
 
16
                  argmax, transpose, newaxis, sort
 
17
 
 
18
from enthought.traits.api import HasStrictTraits, Bool, Enum, Tuple, \
 
19
                             Property, Any, Float
 
20
 
 
21
 
 
22
#-------------------------------------------------------------------
 
23
# Module-specific traits
 
24
#-------------------------------------------------------------------
 
25
 
 
26
# Expresses sorting order of 
 
27
ArraySortTrait = Enum('ascending', 'descending')
 
28
 
 
29
 
 
30
#-------------------------------------------------------------------
 
31
# Module-specific utility functions
 
32
#-------------------------------------------------------------------
 
33
 
 
34
def right_shift(ary, newval):
 
35
    "Returns a right-shifted version of *ary* with *newval* inserted on the left."
 
36
    return concatenate([[newval], ary[:-1]])
 
37
 
 
38
def left_shift(ary, newval):
 
39
    "Returns a left-shifted version of *ary* with *newval* inserted on the right."
 
40
    return concatenate([ary[1:], [newval]])
 
41
 
 
42
def sort_points(points, index=0):
 
43
    """
 
44
    sort_points(array_of_points, index=<0|1>) -> sorted_array
 
45
    
 
46
    Takes a list of points as an Nx2 array and sorts them according
 
47
    to their x-coordinate (index=0) or y-coordinate (index=1).
 
48
    """
 
49
    if len(points.shape) != 2 or (2 not in points.shape):
 
50
        raise RuntimeError, "sort_points(): Array of wrong shape."
 
51
    return take( points, argsort(points[:,index]) )
 
52
 
 
53
def array_zip(*arys):
 
54
    """
 
55
    Returns a Numeric array that is the concatenation of the input 1-D
 
56
    *arys* along a new axis.  This function is basically equivalent to 
 
57
    ``array(zip(*arys))``, but is more resource-efficient.
 
58
    """
 
59
    return transpose(array(arys))
 
60
 
 
61
 
 
62
class AbstractDataMapper(HasStrictTraits):
 
63
    """
 
64
    A data mapper maps from coordinate space to data elements.  In its most
 
65
    basic form, it loops over all the available data points to find the ones
 
66
    near a given coordinate or within an area.  More advanced functionality
 
67
    includes returning rect-aligned "affected regions" enclosing all the
 
68
    returned points, etc.
 
69
    """
 
70
    
 
71
    # How to sort the output list of intersected points that the
 
72
    # get_points_near_*() function returns.  The points are always sorted
 
73
    # by their domain (first/X-value) coordinate.
 
74
    sort_order = ArraySortTrait
 
75
 
 
76
    # A read-only property that describes the origin and size of the data
 
77
    # set in data space as a 4-tuple (min_x, min_y, width, height)
 
78
    extents = Property()
 
79
    
 
80
    
 
81
    #-------------------------------------------------------------------
 
82
    # Private traits
 
83
    #-------------------------------------------------------------------
 
84
    
 
85
    _data = Any
 
86
    
 
87
    # Internally we expect Nx2 arrays; if the user hands in something
 
88
    # different, we stored a transposed version but always remember to
 
89
    # transpose once again whenever we return data.
 
90
    _is_transposed = Bool(False)
 
91
 
 
92
    # the max and min points in data space expressed as a 4-tuple (x,y,w,h)
 
93
    _extents = Tuple
 
94
    
 
95
    # a "fudge factor" to make the extents slightly larger than the actual
 
96
    # values in the data set
 
97
    _extents_delta = Float(0.1)
 
98
    
 
99
    def __init__(self, data=None, data_sorting='none', **kw):
 
100
        "See set_data() for description."
 
101
        self._data = array([])
 
102
        HasStrictTraits.__init__(self, **kw)
 
103
        if data is not None:
 
104
            self.set_data(data, data_sorting)
 
105
        return
 
106
    
 
107
    def get_points_near(self, pointlist, radius=0.0):
 
108
        """
 
109
        get_points_near([points], radius=0.0) -> Nx2 array of candidate points
 
110
        
 
111
        Returns a list of points near the input points (Nx2 array).
 
112
        
 
113
        For each point in the input set, *radius* is used to create a
 
114
        conceptual circle; if any points in the DataMapper's values lie inside
 
115
        this circle, they are returned.
 
116
 
 
117
        The returned list is not guaranteed to be a minimum or exact set,
 
118
        but it is guaranteed to contain all points that intersect the 
 
119
        *pointlist*.  The caller still must do fine-grained testing to see
 
120
        if the points in the returned point list are a match.
 
121
        """
 
122
        raise NotImplementedError
 
123
 
 
124
    def get_points_near_polyline(self, line):
 
125
        """
 
126
        get_points_near_polyline([v1, ... vN]) -> [ [points], [points], ... ]
 
127
        
 
128
        This method is like get_points_near(), except that it takes a polyline 
 
129
        as input.  A polyline is a list of vertices, each connected to the next
 
130
        by a straight line. The polyline has infinitely thin width.  
 
131
        
 
132
        The input array can have shape 2xN or Nx2.
 
133
        """
 
134
        raise NotImplementedError
 
135
    
 
136
    def get_points_in_rect(self, rect):
 
137
        """
 
138
        get_points_in_rect( (x,y,w,h) ) -> [ [points], [points], ... ]
 
139
        
 
140
        This method is like get_points_near(), except that it takes a rectangle
 
141
        as input.  The rectangle has infinitely thin width.
 
142
        """
 
143
        raise NotImplementedError
 
144
    
 
145
    def get_points_in_poly(self, poly):
 
146
        """
 
147
        get_points_in_poly([v1, ... vN]) -> [ [points], [points], ... ]
 
148
        
 
149
        This method is like get_points_near(), except that it takes a polygon 
 
150
        as input.  The polygon has infinitely thin width and can be 
 
151
        self-intersecting and concave.
 
152
        
 
153
        The input array can have shape 2xN or Nx2.
 
154
        """
 
155
        raise NotImplementedError
 
156
 
 
157
    def get_last_region(self):
 
158
        """
 
159
        Returns a region of screen space that contains all of the
 
160
        points/lines/rect/polys in the last get_points_in_*() call.  The
 
161
        region returned by this method is guaranteed to only contain the points
 
162
        that were returned by the previous call.
 
163
        
 
164
        The region is returned as a list of (possibly disjoint) rectangles,
 
165
        where each rectangle is a 4-tuple (x,y,w,h).
 
166
        """
 
167
        raise NotImplementedError
 
168
    
 
169
    def set_data(self, new_data, new_data_sorting='none'):
 
170
        """
 
171
        set_data(new_data, new_data_sorting='none')
 
172
        
 
173
        Sets the data used by this DataMapper.  The *new_data_sorting* parameter
 
174
        indicates how the new data is sorted: 'none', 'ascending', or 'descending'.
 
175
        The default is 'none', which causes the data mapper to perform
 
176
        a full sort of the input data.
 
177
        
 
178
        The input data can be shaped 2xN or Nx2.
 
179
        """
 
180
        if len(new_data) == 0:
 
181
            self.clear()
 
182
            return
 
183
        
 
184
        if new_data.shape[0] == 2:
 
185
            self._is_transposed = True
 
186
            self._data = transpose(new_data)
 
187
        else:
 
188
            self._is_transposed = False
 
189
            self._data = new_data
 
190
        
 
191
        if new_data_sorting == 'none':
 
192
            if self.sort_order == 'ascending':
 
193
                self._data = sort_points(self._data)
 
194
            else:
 
195
                self._data = sort_points(self._data)[::-1]
 
196
        elif new_data_sorting != self.sort_order:
 
197
            self._data = self._data[::-1]
 
198
 
 
199
        self._calc_data_extents()
 
200
        self._update_datamap()
 
201
        # a re-sorting is unnecessary because any internal data structures
 
202
        # will have been updated by the _data update process.
 
203
        return
 
204
 
 
205
    def clear(self):
 
206
        """
 
207
        clear()
 
208
        
 
209
        Resets internal state and any cached data to reflect an empty
 
210
        data set/data space.
 
211
        """
 
212
        self._data = None
 
213
        self._extents = (0,0,0,0)
 
214
        self._clear()
 
215
        return
 
216
 
 
217
    def get_data(self):
 
218
        "Returns the actual data used by the DataMapper."
 
219
        if self._is_transposed:
 
220
            return transpose(self._data)
 
221
        else:
 
222
            return self._data
 
223
 
 
224
    #-------------------------------------------------------------------
 
225
    # Concrete private methods and event handlers
 
226
    # Child classes shouldn't have to override these.
 
227
    #-------------------------------------------------------------------
 
228
    
 
229
    def _get_extents(self):
 
230
        return self._extents
 
231
    
 
232
    def _calc_data_extents(self):
 
233
        """
 
234
        Computes ((minX, minY), (width, height)) of self._data; sets self._extent and
 
235
        returns nothing.
 
236
        """
 
237
        if len(self._data) == 0:
 
238
            self._extents = ((0,0), (0,0))
 
239
        else:
 
240
            value = self._data
 
241
            min_indices = argmin(value, axis=0)
 
242
            max_indices = argmax(value, axis=0)
 
243
            x = value[min_indices[0], 0] - self._extents_delta
 
244
            y = value[min_indices[1], 1] - self._extents_delta
 
245
            maxX = value[max_indices[0], 0] + self._extents_delta
 
246
            maxY = value[max_indices[1], 1] + self._extents_delta
 
247
            self._extents = ((x, y), (maxX-x, maxY-y))
 
248
        return
 
249
 
 
250
 
 
251
    #-------------------------------------------------------------------
 
252
    # Abstract private methods and event handlers
 
253
    #-------------------------------------------------------------------
 
254
    
 
255
    def _update_datamap(self):
 
256
        """
 
257
        This function gets called after self._data has changed.  Child classes
 
258
        should implement this function if they need to recompute any cached
 
259
        data structures, etc.
 
260
        """
 
261
        return
 
262
    
 
263
    def _clear(self):
 
264
        "Performs subclass-specific clearing/cleanup."
 
265
        return
 
266
 
 
267
    def _sort_order_changed(self, old, new):
 
268
        return
 
269
 
 
270
 
 
271
class BruteForceDataMapper(AbstractDataMapper):
 
272
    """
 
273
    The BruteForceDataMapper returns all the points, all the time.
 
274
    This is basically the same behavior as not having a data mapper in
 
275
    the pipeline at all.
 
276
    """
 
277
    
 
278
    def get_points_near(self, pointlist, radius=0):
 
279
        return self.get_data()
 
280
        
 
281
    def get_points_near_polyline(self, line):
 
282
        return self.get_data()
 
283
        
 
284
    def get_points_in_rect(self, rect):
 
285
        return self.get_data()
 
286
    
 
287
    def get_points_in_poly(self, poly):
 
288
        return self.get_data()
 
289
 
 
290
    def get_last_region(self):
 
291
        return self._extents
 
292
 
 
293
    def _sort_order_changed(self, old, new):
 
294
        if len(self._data) == 0:
 
295
            return
 
296
        else:
 
297
            if self.sort_order == 'ascending':
 
298
                self._data = sort_points(self._data)
 
299
            else:
 
300
                self._data = sort_points(self._data)[::-1]
 
301
        return
 
302
 
 
303
#EOF