Debian Codegraph @

examples/tutorials/introduction/4_properties.py

raw
1 # (C) Copyright 2005-2023 Enthought, Inc., Austin, TX
2 # All rights reserved.
3 #
4 # This software is provided without warranty under the terms of the BSD
5 # license included in LICENSE.txt and may be redistributed only under
6 # the conditions described in the aforementioned license. The license
7 # is also available online at http://www.enthought.com/licenses/BSD.txt
8 #
9 # Thanks for using Enthought open source!
10
11 """
12 Property Traits
13 ===============
14
15 The ``Image`` class has three traits which are closely related: ``scan_size``,
16 ``scan_width`` and ``scan_height``. We would ideally like to keep all of these
17 synchronized. This can be done with trait observation, as shown in the
18 previous section, but this sort of pattern is common enough that Traits has
19 some in-built helpers.
20
21 Instead of declaring that ``scan_width = Float()`` we could instead declare it
22 to be a ``Property`` trait type. Property traits are similar to ``@property``
23 decorators in standard Python in that rather than storing a value, they compute
24 a derived value via a "getter", and optionally store values via a "setter".
25 Traits uses specially named methods of the form ``_get_<property>`` and
26 ``_set_property`` for these "getters" and "setters." If there is a "getter"
27 but no "setter" then the property is read-only.
28
29 Additionally, we need to know when the value of the property might change, and
30 so we need to declare what traits to observe to know when the property might
31 change. What all this means is that we can define ``scan_width`` as a
32 property by::
33
34 class Image(HasTraits):
35 ...
36
37 scan_width = Property(Float, depends_on='scan_size')
38
39 def _get_scan_width(self):
40 return self.scan_size[0]
41
42 def _set_scan_width(self, value):
43 self.scan_size = (value, self.scan_height)
44
45 Traits will then take care of hooking up all the required observers to make
46 everything work as expected; and the `Property` can also be observed if
47 desired.
48
49 Simple `Property` traits like this are computed "lazily": the value is only
50 calculated when you ask for it.
51
52 Cached Properties
53 -----------------
54
55 It would be quite easy to turn the histogram function into a read-only
56 property. This might look something like this::
57
58 class Image(HasTraits):
59 ...
60
61 histogram = Property(Array, depends_on='image')
62
63 def _get_histogram(self):
64 hist, bins = np.histogram(
65 self.image,
66 bins=256,
67 range=(0, 256),
68 density=True,
69 )
70 return hist
71
72 This works, but it has a downside that the histogram is re-computed every
73 time the property is accessed. For small images, this is probably OK, but
74 for larger images, or if you are working with many images at once, this may
75 impact performance. In these cases, you can specify that the property
76 should **cache** the returned value and use that value until the trait(s)
77 the property depend on changes::
78
79 class Image(HasTraits):
80 ...
81
82 histogram = Property(Array, depends_on='image')
83
84 @cached_property
85 def _get_histogram(self):
86 hist, bins = np.histogram(
87 self.image,
88 bins=256,
89 range=(0, 256),
90 density=True,
91 )
92 return hist
93
94 This has the trade-off that the result of the computation is being stored
95 in memory, but in this case the memory is only a few hundred bytes, and so
96 is unlikely to cause problems; but you probably wouldn't want to do this
97 with a multi-gigabyte array.
98
99 Exercise
100 --------
101
102 Make ``pixel_area`` a read-only property.
103
104 """
105
106 import os
107 import datetime
108
109 from PIL import Image as PILImage
110 import numpy as np
111
112 from traits.api import (
113 Array, Date, File, Float, HasTraits, Property, Str, Tuple,
114 cached_property, observe
115 )
116
117
118 class Image(HasTraits):
119 """ An SEM image stored in a file. """
120
121 filename = File(exists=True)
122 sample_id = Str()
123 operator = Str("N/A")
124 date_acquired = Date()
125 scan_size = Tuple(Float, Float)
126
127 scan_width = Property(Float, depends_on='scan_size')
128 scan_height = Property(Float, depends_on='scan_size')
129
130 image = Array(shape=(None, None), dtype='uint8')
131 histogram = Property(Array, depends_on='image')
132
133 pixel_area = Float()
134
135 # Trait observers
136
137 @observe('filename')
138 def read_image(self, event):
139 pil_image = PILImage.open(self.filename).convert("L")
140 self.image = np.array(pil_image)
141
142 # compute some extra secondary attributes from the image
143 if self.image.size > 0:
144 self.pixel_area = (
145 self.scan_height * self.scan_width / self.image.size
146 )
147 else:
148 self.pixel_area = 0
149
150 # Trait default methods
151
152 def _date_acquired_default(self):
153 return datetime.date.today()
154
155 def _scan_size_default(self):
156 return (1e-5, 1e-5)
157
158 # Trait property methods
159
160 def _get_scan_width(self):
161 return self.scan_size[0]
162
163 def _set_scan_width(self, value):
164 self.scan_size = (value, self.scan_size[1])
165
166 def _get_scan_height(self):
167 return self.scan_size[1]
168
169 def _set_scan_height(self, value):
170 self.scan_size = (self.scan_size[0], value)
171
172 @cached_property
173 def _get_histogram(self):
174 hist, bins = np.histogram(
175 self.image,
176 bins=256,
177 range=(0, 256),
178 density=True,
179 )
180 return hist
181
182
183 # ---------------------------------------------------------------------------
184 # Demo code
185 # ---------------------------------------------------------------------------
186
187 this_dir = os.path.dirname(__file__)
188 image_dir = os.path.join(this_dir, "images")
189 filename = os.path.join(image_dir, "sample_0001.png")
190
191 # load the image
192 image = Image(
193 filename=filename,
194 operator="Hannes",
195 sample_id="0001",
196 )
197
198 # perform some sample computations
199 print("Scan size:", image.scan_size)
200
201 print("Change scan width to 1e-4")
202 image.scan_width = 1e-4
203
204 print("Scan size:", image.scan_size)
205
206 for filename in os.listdir(image_dir):
207 if os.path.splitext(filename)[1] == '.png':
208 print()
209 print("Changing filename to {}".format(filename))
210 image.filename = os.path.join(image_dir, filename)
211
212 print(
213 "The most frequent intensity of {} is {}".format(
214 filename,
215 image.histogram.argmax(),
216 )
217 )