Debian Codegraph @

traits/examples/introduction/3_observation.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 Observation
13 ===========
14
15 In our code so far, there is a problem that it is possible for certain related
16 values to get out of sync with one another. For example, if we change the
17 filename after we have read the image into memory, then the data in memory
18 still refers to the old image. It would be nice if we could automatically
19 re-load the image if the filename changes. Traits allows you to do this.
20
21 The Observe Decorator
22 ---------------------
23
24 We want to have the `read_image` method run whenever the ``filename`` trait
25 changes. We can do this by adding an ``observe`` decorator to the method::
26
27
28 class Image(HasTraits):
29 ...
30
31 @observe('filename')
32 def read_image(self, event):
33 ...
34
35 The observer passes an event object to the function which contains information
36 about what changed, such as the old value of the trait, but we don't need that
37 information to react to the change, so it is ignored in the body of the
38 function.
39
40 For most traits, the observer will run only when the trait's value *actually*
41 changes, not just when the value is set. So if you do::
42
43 >>> image.filename = "sample_0001.png"
44 >>> image.filename = "sample_0001.png"
45
46 then the observer will only be run once.
47
48 Observing Multiple Traits
49 -------------------------
50
51 If you look at the computation of ``pixel_area`` in the original code, it
52 looks like this::
53
54 self.pixel_area = self.scan_height * self.scan_width / self.image.size
55
56 It depends on the ``scan_width``, ``scan_height`` and the ``image``, so we
57 would like to listen to changes to *all* of these. We could write three
58 ``@observe`` functions, one for each trait, but the content would be the
59 same for each. A better way to do this is to have the observer listen to
60 all the traits at once::
61
62
63 class Image(HasTraits):
64 ...
65
66 @observe('scan_width, scan_height, image')
67 def update_pixel_area(self, event):
68 if self.image.size > 0:
69 self.pixel_area = (
70 self.scan_height * self.scan_width / self.image.size
71 )
72 else:
73 self.pixel_area = 0
74
75 Dynamic Observers
76 -----------------
77
78 Sometimes you want to be able to observe changes to traits from a different
79 object or piece of code. The ``observe`` method on a ``HasTraits`` subclass
80 allows you to dynamically specify a function to be called if the value of a
81 trait changes::
82
83 image = Image(
84 filename="sample_0001.png",
85 sample_id="0001",
86 )
87
88 def print_filename_changed(event):
89 print("Filename changed")
90
91 image.observe(print_filename_changed, 'filename')
92
93 # will print "Filename changed" to the screen
94 image.filename="sample_0002.png"
95
96 Dynamic observers can also be disconnected using the same method, by adding
97 the argument ``remove=True``::
98
99 image.observe(print_filename_changed, 'filename', remove=True)
100
101 # nothing will print
102 image.filename="sample_0003.png"
103
104 Exercise
105 --------
106
107 Currently ``scan_height`` and ``scan_width`` are set from the parts of the
108 ``scan_size`` trait as part of the ``traits_init`` method. Remove the
109 ``traits_init`` method and have ``scan_height`` and ``scan_width`` methods
110 update whenever ``scan_size`` changes.
111
112 """
113
114 import os
115 import datetime
116
117 from PIL import Image as PILImage
118 import numpy as np
119
120 from traits.api import (
121 Array, Date, File, Float, HasTraits, Str, Tuple, observe
122 )
123
124
125 class Image(HasTraits):
126 """ An SEM image stored in a file. """
127
128 filename = File(exists=True)
129 sample_id = Str()
130 operator = Str("N/A")
131 date_acquired = Date()
132 scan_size = Tuple(Float, Float)
133
134 scan_width = Float
135 scan_height = Float
136
137 image = Array(shape=(None, None), dtype='uint8')
138
139 pixel_area = Float()
140
141 def traits_init(self):
142 # useful secondary attributes
143 self.scan_width, self.scan_height = self.scan_size
144
145 # Trait observers
146
147 @observe('filename')
148 def read_image(self, event):
149 pil_image = PILImage.open(self.filename).convert("L")
150 self.image = np.array(pil_image)
151
152 @observe('scan_width, scan_height, image')
153 def update_pixel_area(self, event):
154 if self.image.size > 0:
155 self.pixel_area = (
156 self.scan_height * self.scan_width / self.image.size
157 )
158 else:
159 self.pixel_area = 0
160
161 # Trait default methods
162
163 def _date_acquired_default(self):
164 return datetime.date.today()
165
166 def _scan_size_default(self):
167 return (1e-5, 1e-5)
168
169
170 # ---------------------------------------------------------------------------
171 # Demo code
172 # ---------------------------------------------------------------------------
173
174 this_dir = os.path.dirname(__file__)
175 image_dir = os.path.join(this_dir, "images")
176 filename = os.path.join(image_dir, "sample_0001.png")
177
178 # load the image
179 image = Image(
180 filename=filename,
181 operator="Hannes",
182 sample_id="0001",
183 )
184
185 # perform some sample computations
186 print("Scan size:", image.scan_size)
187
188 print("Change scan width to 1e-4")
189 image.scan_width = 1e-4
190
191 print("Scan size:", image.scan_size)
192
193 for filename in os.listdir(image_dir):
194 if os.path.splitext(filename)[1] == '.png':
195 print()
196 print("Changing filename to {}".format(filename))
197 image.filename = os.path.join(image_dir, filename)
198
199 print(
200 "The pixel size of {} is {:0.3f} nm²".format(
201 filename,
202 image.pixel_area * 1e18,
203 )
204 )