Debian Codegraph @

traits/examples/introduction/5_documentation.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 Documentation
13 =============
14
15 Another advantage of using Traits is that you code becomes clearer and easier
16 for yourself and other people to work with. If you look at the original
17 version of the image class, it isn't clear what attributes are available on
18 the class and, worse yet, it isn't clear *when* those attributes are available.
19
20 Self-Documenting Code
21 ---------------------
22
23 By using Traits, all your attributes are declared up-front, so anyone reading
24 your class knows exactly what your class is providing::
25
26 class Image(HasTraits):
27 filename = File(exists=True)
28 sample_id = Str()
29 operator = Str("N/A")
30 date_acquired = Date()
31 scan_size = Tuple(Float, Float)
32 scan_width = Property(Float, depends_on='scan_size')
33 scan_height = Property(Float, depends_on='scan_size')
34 image = Array(shape=(None, None), dtype='uint8')
35 pixel_area = Property(Float, depends_on='scan_height,scan_width,image')
36 histogram = Property(Array, depends_on='image')
37
38 This goes a long way towards the ideal of "self-documenting code." It is
39 common in production-quality Traits code to also document each trait with a
40 special ``#:`` comment so that auto-documentation tools like Sphinx can
41 generate API documentation for you::
42
43 class Image(HasTraits):
44
45 #: The filename of the image.
46 filename = File(exists=True)
47
48 #: The ID of the sample that is being imaged.
49 sample_id = Str()
50
51 #: The name of the operator who acquired the image.
52 operator = Str("N/A")
53
54 ...
55
56
57 HasStrictTraits
58 ---------------
59
60 One common class of errors in Python are typos when accessing an attribute
61 of a class. For example, if we typed::
62
63 >>> image.fileanme = "sample_0002.png"
64
65 Python will not throw an error, but the code will not have the effect that
66 the user expects. Some development tools can help you detect these
67 sorts of errors, but most of these are not available when writing code
68 interactively, such as in a Jupyter notebook.
69
70 Traits provides a special subclass of ``HasTraits`` called ``HasStrictTraits``
71 which restricts the allowed attributes to **only** the traits on the class.
72 If we use::
73
74 class Image(HasStrictTraits):
75 ...
76
77 then if we type::
78
79 >>> image.fileanme = "sample_0002.png"
80 TraitError: Cannot set the undefined 'fileanme' attribute of a 'Image'
81 object.
82
83 We get an immediate error which flags the problem.
84
85 """
86
87 import os
88 import datetime
89
90 from PIL import Image as PILImage
91 import numpy as np
92
93 from traits.api import (
94 Array, Date, File, Float, HasStrictTraits, Property, Str, Tuple,
95 cached_property, observe
96 )
97
98
99 class Image(HasStrictTraits):
100 """ An SEM image stored in a file. """
101
102 #: The filename of the image.
103 filename = File(exists=True)
104
105 #: The ID of the sample that is being imaged.
106 sample_id = Str()
107
108 #: The name of the operator who acquired the image.
109 operator = Str("N/A")
110
111 #: The date the image was acquired.
112 date_acquired = Date()
113
114 #: The size of the image.
115 scan_size = Tuple(Float, Float)
116
117 #: The width of the image.
118 scan_width = Property(Float, depends_on='scan_size')
119
120 #: The height of the image.
121 scan_height = Property(Float, depends_on='scan_size')
122
123 #: The image as a 2D numpy array
124 image = Array(shape=(None, None), dtype='uint8')
125
126 #: The area of each pixel.
127 pixel_area = Property(Float, depends_on='scan_height,scan_width,image')
128
129 #: The histogram of pixel intensities.
130 histogram = Property(Array, depends_on='image')
131
132 def threshold(self, low=0, high=255):
133 """ Compute a threshold mask for the array. """
134 return (self.image >= low) & (self.image <= high)
135
136 # Trait observers
137
138 @observe('filename')
139 def read_image(self, event):
140 pil_image = PILImage.open(self.filename).convert("L")
141 self.image = np.array(pil_image)
142
143 # Trait default methods
144
145 def _date_acquired_default(self):
146 return datetime.date.today()
147
148 def _scan_size_default(self):
149 return (1e-5, 1e-5)
150
151 # Trait property methods
152
153 def _get_scan_width(self):
154 return self.scan_size[0]
155
156 def _set_scan_width(self, value):
157 self.scan_size = (value, self.scan_size[1])
158
159 def _get_scan_height(self):
160 return self.scan_size[1]
161
162 def _set_scan_height(self, value):
163 self.scan_size = (self.scan_size[0], value)
164
165 def _get_pixel_area(self):
166 if self.image.size > 0:
167 return self.scan_height * self.scan_width / self.image.size
168 else:
169 return 0
170
171 @cached_property
172 def _get_histogram(self):
173 hist, bins = np.histogram(
174 self.image,
175 bins=256,
176 range=(0, 256),
177 density=True,
178 )
179 return hist
180
181
182 # ---------------------------------------------------------------------------
183 # Demo code
184 # ---------------------------------------------------------------------------
185
186 this_dir = os.path.dirname(__file__)
187 image_dir = os.path.join(this_dir, "images")
188 filename = os.path.join(image_dir, "sample_0001.png")
189
190 # load the image
191 image = Image(
192 filename=filename,
193 operator="Hannes",
194 sample_id="0001",
195 date_acquired=datetime.datetime.today(),
196 scan_size=(1e-5, 1e-5),
197 )
198
199 # perform some sample computations
200 print(
201 "The maximum intensity of {} is {}".format(
202 image.sample_id,
203 image.histogram.argmax(),
204 )
205 )
206 pixel_count = image.threshold(low=200).sum()
207 print(
208 "The area with intensity greater than 200 is {:0.3f} µm²".format(
209 pixel_count * image.pixel_area * 1e12
210 )
211 )