##// END OF EJS Templates
Work on examples and fixed a super subtle bug in Component....
bgranger -
Show More
@@ -1,337 +1,346 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 A lightweight component system for IPython.
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10 """
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Copyright (C) 2008-2009 The IPython Development Team
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #-----------------------------------------------------------------------------
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Imports
21 21 #-----------------------------------------------------------------------------
22 22
23 23 from copy import deepcopy
24 24 import datetime
25 25 from weakref import WeakValueDictionary
26 26
27 27 from IPython.utils.importstring import import_item
28 28 from IPython.config.loader import Config
29 29 from IPython.utils.traitlets import (
30 30 HasTraitlets, TraitletError, MetaHasTraitlets, Instance, This
31 31 )
32 32
33 33
34 34 #-----------------------------------------------------------------------------
35 35 # Helper classes for Components
36 36 #-----------------------------------------------------------------------------
37 37
38 38
39 39 class ComponentError(Exception):
40 40 pass
41 41
42 42 class MetaComponentTracker(type):
43 43 """A metaclass that tracks instances of Components and its subclasses."""
44 44
45 45 def __init__(cls, name, bases, d):
46 46 super(MetaComponentTracker, cls).__init__(name, bases, d)
47 47 cls.__instance_refs = WeakValueDictionary()
48 48 cls.__numcreated = 0
49 49
50 50 def __call__(cls, *args, **kw):
51 51 """Called when a class is called (instantiated)!!!
52 52
53 53 When a Component or subclass is instantiated, this is called and
54 54 the instance is saved in a WeakValueDictionary for tracking.
55 55 """
56 56 instance = cls.__new__(cls, *args, **kw)
57 57
58 58 # Register the instance before __init__ is called so get_instances
59 59 # works inside __init__ methods!
60 60 indices = cls.register_instance(instance)
61 61
62 62 # This is in a try/except because of the __init__ method fails, the
63 63 # instance is discarded and shouldn't be tracked.
64 64 try:
65 65 if isinstance(instance, cls):
66 66 cls.__init__(instance, *args, **kw)
67 67 except:
68 68 # Unregister the instance because __init__ failed!
69 69 cls.unregister_instances(indices)
70 70 raise
71 71 else:
72 72 return instance
73 73
74 74 def register_instance(cls, instance):
75 75 """Register instance with cls and its subclasses."""
76 76 # indices is a list of the keys used to register the instance
77 77 # with. This list is needed if the instance needs to be unregistered.
78 78 indices = []
79 79 for c in cls.__mro__:
80 80 if issubclass(cls, c) and issubclass(c, Component):
81 81 c.__numcreated += 1
82 82 indices.append(c.__numcreated)
83 83 c.__instance_refs[c.__numcreated] = instance
84 84 else:
85 85 break
86 86 return indices
87 87
88 88 def unregister_instances(cls, indices):
89 89 """Unregister instance with cls and its subclasses."""
90 90 for c, index in zip(cls.__mro__, indices):
91 91 try:
92 92 del c.__instance_refs[index]
93 93 except KeyError:
94 94 pass
95 95
96 96 def clear_instances(cls):
97 97 """Clear all instances tracked by cls."""
98 98 cls.__instance_refs.clear()
99 99 cls.__numcreated = 0
100 100
101 101 def get_instances(cls, name=None, root=None, klass=None):
102 102 """Get all instances of cls and its subclasses.
103 103
104 104 Parameters
105 105 ----------
106 106 name : str
107 107 Limit to components with this name.
108 108 root : Component or subclass
109 109 Limit to components having this root.
110 110 klass : class or str
111 111 Limits to instances of the class or its subclasses. If a str
112 112 is given ut must be in the form 'foo.bar.MyClass'. The str
113 113 form of this argument is useful for forward declarations.
114 114 """
115 115 if klass is not None:
116 116 if isinstance(klass, basestring):
117 117 klass = import_item(klass)
118 118 # Limit search to instances of klass for performance
119 119 if issubclass(klass, Component):
120 120 return klass.get_instances(name=name, root=root)
121 121 instances = cls.__instance_refs.values()
122 122 if name is not None:
123 123 instances = [i for i in instances if i.name == name]
124 124 if klass is not None:
125 125 instances = [i for i in instances if isinstance(i, klass)]
126 126 if root is not None:
127 127 instances = [i for i in instances if i.root == root]
128 128 return instances
129 129
130 130 def get_instances_by_condition(cls, call, name=None, root=None,
131 131 klass=None):
132 132 """Get all instances of cls, i such that call(i)==True.
133 133
134 134 This also takes the ``name`` and ``root`` and ``classname``
135 135 arguments of :meth:`get_instance`
136 136 """
137 137 return [i for i in cls.get_instances(name, root, klass) if call(i)]
138 138
139 139
140 140 def masquerade_as(instance, cls):
141 141 """Let instance masquerade as an instance of cls.
142 142
143 143 Sometimes, such as in testing code, it is useful to let a class
144 144 masquerade as another. Python, being duck typed, allows this by
145 145 default. But, instances of components are tracked by their class type.
146 146
147 147 After calling this, ``cls.get_instances()`` will return ``instance``. This
148 148 does not, however, cause ``isinstance(instance, cls)`` to return ``True``.
149 149
150 150 Parameters
151 151 ----------
152 152 instance : an instance of a Component or Component subclass
153 153 The instance that will pretend to be a cls.
154 154 cls : subclass of Component
155 155 The Component subclass that instance will pretend to be.
156 156 """
157 157 cls.register_instance(instance)
158 158
159 159
160 160 class ComponentNameGenerator(object):
161 161 """A Singleton to generate unique component names."""
162 162
163 163 def __init__(self, prefix):
164 164 self.prefix = prefix
165 165 self.i = 0
166 166
167 167 def __call__(self):
168 168 count = self.i
169 169 self.i += 1
170 170 return "%s%s" % (self.prefix, count)
171 171
172 172
173 173 ComponentNameGenerator = ComponentNameGenerator('ipython.component')
174 174
175 175
176 176 class MetaComponent(MetaHasTraitlets, MetaComponentTracker):
177 177 pass
178 178
179 179
180 180 #-----------------------------------------------------------------------------
181 181 # Component implementation
182 182 #-----------------------------------------------------------------------------
183 183
184 184
185 185 class Component(HasTraitlets):
186 186
187 187 __metaclass__ = MetaComponent
188 188
189 189 # Traitlets are fun!
190 190 config = Instance(Config,(),{})
191 191 parent = This()
192 192 root = This()
193 193 created = None
194 194
195 195 def __init__(self, parent, name=None, config=None):
196 196 """Create a component given a parent and possibly and name and config.
197 197
198 198 Parameters
199 199 ----------
200 200 parent : Component subclass
201 201 The parent in the component graph. The parent is used
202 202 to get the root of the component graph.
203 203 name : str
204 204 The unique name of the component. If empty, then a unique
205 205 one will be autogenerated.
206 206 config : Config
207 207 If this is empty, self.config = parent.config, otherwise
208 208 self.config = config and root.config is ignored. This argument
209 209 should only be used to *override* the automatic inheritance of
210 210 parent.config. If a caller wants to modify parent.config
211 211 (not override), the caller should make a copy and change
212 212 attributes and then pass the copy to this argument.
213 213
214 214 Notes
215 215 -----
216 216 Subclasses of Component must call the :meth:`__init__` method of
217 217 :class:`Component` *before* doing anything else and using
218 218 :func:`super`::
219 219
220 220 class MyComponent(Component):
221 221 def __init__(self, parent, name=None, config=None):
222 222 super(MyComponent, self).__init__(parent, name, config)
223 223 # Then any other code you need to finish initialization.
224 224
225 225 This ensures that the :attr:`parent`, :attr:`name` and :attr:`config`
226 226 attributes are handled properly.
227 227 """
228 228 super(Component, self).__init__()
229 229 self._children = []
230 230 if name is None:
231 231 self.name = ComponentNameGenerator()
232 232 else:
233 233 self.name = name
234 234 self.root = self # This is the default, it is set when parent is set
235 235 self.parent = parent
236 236 if config is not None:
237 237 self.config = config
238 238 # We used to deepcopy, but for now we are trying to just save
239 239 # by reference. This *could* have side effects as all components
240 # will share config.
240 # will share config. In fact, I did find such a side effect in
241 # _config_changed below. If a config attribute value was a mutable type
242 # all instances of a component were getting the same copy, effectively
243 # making that a class attribute.
241 244 # self.config = deepcopy(config)
242 245 else:
243 246 if self.parent is not None:
244 247 self.config = self.parent.config
245 248 # We used to deepcopy, but for now we are trying to just save
246 249 # by reference. This *could* have side effects as all components
247 # will share config.
250 # will share config. In fact, I did find such a side effect in
251 # _config_changed below. If a config attribute value was a mutable type
252 # all instances of a component were getting the same copy, effectively
253 # making that a class attribute.
248 254 # self.config = deepcopy(self.parent.config)
249 255
250 256 self.created = datetime.datetime.now()
251 257
252 258 #-------------------------------------------------------------------------
253 259 # Static traitlet notifiations
254 260 #-------------------------------------------------------------------------
255 261
256 262 def _parent_changed(self, name, old, new):
257 263 if old is not None:
258 264 old._remove_child(self)
259 265 if new is not None:
260 266 new._add_child(self)
261 267
262 268 if new is None:
263 269 self.root = self
264 270 else:
265 271 self.root = new.root
266 272
267 273 def _root_changed(self, name, old, new):
268 274 if self.parent is None:
269 275 if not (new is self):
270 276 raise ComponentError("Root not self, but parent is None.")
271 277 else:
272 278 if not self.parent.root is new:
273 279 raise ComponentError("Error in setting the root attribute: "
274 280 "root != parent.root")
275 281
276 282 def _config_changed(self, name, old, new):
277 283 """Update all the class traits having ``config=True`` as metadata.
278 284
279 285 For any class traitlet with a ``config`` metadata attribute that is
280 286 ``True``, we update the traitlet with the value of the corresponding
281 287 config entry.
282 288 """
283 289 # Get all traitlets with a config metadata entry that is True
284 290 traitlets = self.traitlets(config=True)
285 291
286 292 # We auto-load config section for this class as well as any parent
287 293 # classes that are Component subclasses. This starts with Component
288 294 # and works down the mro loading the config for each section.
289 295 section_names = [cls.__name__ for cls in \
290 296 reversed(self.__class__.__mro__) if
291 297 issubclass(cls, Component) and issubclass(self.__class__, cls)]
292 298
293 299 for sname in section_names:
294 300 # Don't do a blind getattr as that would cause the config to
295 301 # dynamically create the section with name self.__class__.__name__.
296 302 if new._has_section(sname):
297 303 my_config = new[sname]
298 304 for k, v in traitlets.items():
299 305 # Don't allow traitlets with config=True to start with
300 306 # uppercase. Otherwise, they are confused with Config
301 307 # subsections. But, developers shouldn't have uppercase
302 308 # attributes anyways! (PEP 6)
303 309 if k[0].upper()==k[0] and not k.startswith('_'):
304 310 raise ComponentError('Component traitlets with '
305 311 'config=True must start with a lowercase so they are '
306 312 'not confused with Config subsections: %s.%s' % \
307 313 (self.__class__.__name__, k))
308 314 try:
309 315 # Here we grab the value from the config
310 316 # If k has the naming convention of a config
311 317 # section, it will be auto created.
312 318 config_value = my_config[k]
313 319 except KeyError:
314 320 pass
315 321 else:
316 322 # print "Setting %s.%s from %s.%s=%r" % \
317 323 # (self.__class__.__name__,k,sname,k,config_value)
318 setattr(self, k, config_value)
324 # We have to do a deepcopy here if we don't deepcopy the entire
325 # config object. If we don't, a mutable config_value will be
326 # shared by all instances, effectively making it a class attribute.
327 setattr(self, k, deepcopy(config_value))
319 328
320 329 @property
321 330 def children(self):
322 331 """A list of all my child components."""
323 332 return self._children
324 333
325 334 def _remove_child(self, child):
326 335 """A private method for removing children components."""
327 336 if child in self._children:
328 337 index = self._children.index(child)
329 338 del self._children[index]
330 339
331 340 def _add_child(self, child):
332 341 """A private method for adding children components."""
333 342 if child not in self._children:
334 343 self._children.append(child)
335 344
336 345 def __repr__(self):
337 346 return "<%s('%s')>" % (self.__class__.__name__, self.name)
@@ -1,66 +1,66 b''
1 1 """Count the frequencies of words in a string"""
2 2
3 3 from __future__ import division
4 4
5 5 import cmath as math
6 6
7 7
8 8 def wordfreq(text):
9 9 """Return a dictionary of words and word counts in a string."""
10 10
11 11 freqs = {}
12 12 for word in text.split():
13 13 lword = word.lower()
14 14 freqs[lword] = freqs.get(lword, 0) + 1
15 15 return freqs
16 16
17 17
18 18 def print_wordfreq(freqs, n=10):
19 19 """Print the n most common words and counts in the freqs dict."""
20 20
21 21 words, counts = freqs.keys(), freqs.values()
22 22 items = zip(counts, words)
23 23 items.sort(reverse=True)
24 24 for (count, word) in items[:n]:
25 25 print word, count
26 26
27 27
28 def wordfreq_to_weightsize(worddict, minsize=10, maxsize=50, minalpha=0.4, maxalpha=1.0):
28 def wordfreq_to_weightsize(worddict, minsize=25, maxsize=50, minalpha=0.5, maxalpha=1.0):
29 29 mincount = min(worddict.itervalues())
30 30 maxcount = max(worddict.itervalues())
31 31 weights = {}
32 32 for k, v in worddict.iteritems():
33 33 w = (v-mincount)/(maxcount-mincount)
34 34 alpha = minalpha + (maxalpha-minalpha)*w
35 35 size = minsize + (maxsize-minsize)*w
36 36 weights[k] = (alpha, size)
37 37 return weights
38 38
39 39
40 def tagcloud(worddict, n=10, minsize=10, maxsize=50, minalpha=0.4, maxalpha=1.0):
40 def tagcloud(worddict, n=10, minsize=25, maxsize=50, minalpha=0.5, maxalpha=1.0):
41 41 from matplotlib import pyplot as plt
42 42 import random
43 43
44 44 worddict = wordfreq_to_weightsize(worddict, minsize, maxsize, minalpha, maxalpha)
45 45
46 46 fig = plt.figure()
47 47 ax = fig.add_subplot(111)
48 48 ax.set_position([0.0,0.0,1.0,1.0])
49 49 plt.xticks([])
50 50 plt.yticks([])
51 51
52 52 words = worddict.keys()
53 53 alphas = [v[0] for v in worddict.values()]
54 54 sizes = [v[1] for v in worddict.values()]
55 55 items = zip(alphas, sizes, words)
56 56 items.sort(reverse=True)
57 57 for alpha, size, word in items[:n]:
58 xpos = random.normalvariate(0.5, 0.3)
59 ypos = random.normalvariate(0.5, 0.3)
60 # xpos = random.uniform(0.0,1.0)
61 # ypos = random.uniform(0.0,1.0)
58 # xpos = random.normalvariate(0.5, 0.3)
59 # ypos = random.normalvariate(0.5, 0.3)
60 xpos = random.uniform(0.0,1.0)
61 ypos = random.uniform(0.0,1.0)
62 62 ax.text(xpos, ypos, word.lower(), alpha=alpha, fontsize=size)
63 63 ax.autoscale_view()
64 64 return ax
65 65
66 66 No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now