forked from swcarpentry/python-novice-inflammation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
discussion.html
223 lines (219 loc) · 18.8 KB
/
discussion.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<title>Software Carpentry: Programming with Python</title>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap-theme.css" />
<link rel="stylesheet" type="text/css" href="css/swc.css" />
<link rel="alternate" type="application/rss+xml" title="Software Carpentry Blog" href="http://software-carpentry.org/feed.xml"/>
<meta charset="UTF-8" />
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body class="lesson">
<div class="container card">
<div class="banner">
<a href="http://software-carpentry.org" title="Software Carpentry">
<img alt="Software Carpentry banner" src="img/software-carpentry-banner.png" />
</a>
</div>
<article>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<a href="index.html"><h1 class="title">Programming with Python</h1></a>
<h2 class="subtitle">Discussion</h2>
<h2 id="rules-of-debugging">Rules of Debugging</h2>
<ol style="list-style-type: decimal">
<li>Fail early, fail often.</li>
<li>Always initialize from data.</li>
<li>Know what it’s supposed to do.</li>
<li>Make it fail every time.</li>
<li>Make it fail fast.</li>
<li>Change one thing at a time, for a reason.</li>
<li>Keep track of what we’ve done.</li>
<li>Be humble.</li>
<li>Test the simple things first.</li>
</ol>
<p>And remember, a week of hard work can sometimes save you an hour of thought.</p>
<h2 id="the-call-stack">The Call Stack</h2>
<p>Let’s take a closer look at what happens when we call <code>fahr_to_celsius(32.0)</code>. To make things clearer, we’ll start by putting the initial value 32.0 in a variable and store the final result in one as well:</p>
<pre class="sourceCode python"><code class="sourceCode python">original = <span class="fl">32.0</span>
final = fahr_to_celsius(original)</code></pre>
<p>The diagram below shows what memory looks like after the first line has been executed:</p>
<p><img src="fig/python-call-stack-01.svg" alt="Call Stack (Initial State)" /><br /> When we call <code>fahr_to_celsius</code>, Python <em>doesn’t</em> create the variable <code>temp</code> right away. Instead, it creates something called a <a href="reference.html#stack-frame">stack frame</a> to keep track of the variables defined by <code>fahr_to_kelvin</code>. Initially, this stack frame only holds the value of <code>temp</code>:</p>
<p><img src="fig/python-call-stack-02.svg" alt="Call Stack Immediately After First Function Call" /><br /> When we call <code>fahr_to_kelvin</code> inside <code>fahr_to_celsius</code>, Python creates another stack frame to hold <code>fahr_to_kelvin</code>’s variables:</p>
<p><img src="fig/python-call-stack-03.svg" alt="Call Stack During First Nested Function Call" /><br /> It does this because there are now two variables in play called <code>temp</code>: the parameter to <code>fahr_to_celsius</code>, and the parameter to <code>fahr_to_kelvin</code>. Having two variables with the same name in the same part of the program would be ambiguous, so Python (and every other modern programming language) creates a new stack frame for each function call to keep that function’s variables separate from those defined by other functions.</p>
<p>When the call to <code>fahr_to_kelvin</code> returns a value, Python throws away <code>fahr_to_kelvin</code>’s stack frame and creates a new variable in the stack frame for <code>fahr_to_celsius</code> to hold the temperature in Kelvin:</p>
<p><img src="fig/python-call-stack-04.svg" alt="Call Stack After Return From First Nested Function Call" /><br /> It then calls <code>kelvin_to_celsius</code>, which means it creates a stack frame to hold that function’s variables:</p>
<p><img src="fig/python-call-stack-05.svg" alt="Call Stack During Call to Second Nested Function" /><br /> Once again, Python throws away that stack frame when <code>kelvin_to_celsius</code> is done and creates the variable <code>result</code> in the stack frame for <code>fahr_to_celsius</code>:</p>
<p><img src="fig/python-call-stack-06.svg" alt="Call Stack After Second Nested Function Returns" /><br /> Finally, when <code>fahr_to_celsius</code> is done, Python throws away <em>its</em> stack frame and puts its result in a new variable called <code>final</code> that lives in the stack frame we started with:</p>
<p><img src="fig/python-call-stack-07.svg" alt="Call Stack After All Functions Have Finished" /><br /> This final stack frame is always there; it holds the variables we defined outside the functions in our code. What it <em>doesn’t</em> hold is the variables that were in the various stack frames. If we try to get the value of <code>temp</code> after our functions have finished running, Python tells us that there’s no such thing:</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="dt">print</span>(<span class="st">'final value of temp after all function calls:'</span>, temp)</code></pre>
<pre class="error"><code>---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-12-ffd9b4dbd5f1> in <module>()
----> 1 print('final value of temp after all function calls:', temp)
NameError: name 'temp' is not defined</code></pre>
<pre class="output"><code>final value of temp after all function calls:</code></pre>
<p>Why go to all this trouble? Well, here’s a function called <code>span</code> that calculates the difference between the mininum and maximum values in an array:</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="ch">import</span> numpy
<span class="kw">def</span> span(a):
diff = a.<span class="dt">max</span>() - a.<span class="dt">min</span>()
<span class="kw">return</span> diff
data = numpy.loadtxt(fname=<span class="st">'inflammation-01.csv'</span>, delimiter=<span class="st">','</span>)
<span class="dt">print</span>(<span class="st">'span of data:'</span>, span(data))</code></pre>
<pre class="output"><code>span of data: 20.0</code></pre>
<p>Notice that <code>span</code> assigns a value to a variable called <code>diff</code>. We might very well use a variable with the same name to hold data:</p>
<pre class="sourceCode python"><code class="sourceCode python">diff = numpy.loadtxt(fname=<span class="st">'inflammation-01.csv'</span>, delimiter=<span class="st">','</span>)
<span class="dt">print</span>(<span class="st">'span of data:'</span>, span(diff))</code></pre>
<pre class="output"><code>span of data: 20.0</code></pre>
<p>We don’t expect <code>diff</code> to have the value 20.0 after this function call, so the name <code>diff</code> cannot refer to the same thing inside <code>span</code> as it does in the main body of our program. And yes, we could probably choose a different name than <code>diff</code> in our main program in this case, but we don’t want to have to read every line of NumPy to see what variable names its functions use before calling any of those functions, just in case they change the values of our variables.</p>
<p>The big idea here is <a href="reference.html#encapsulation">encapsulation</a>, and it’s the key to writing correct, comprehensible programs. A function’s job is to turn several operations into one so that we can think about a single function call instead of a dozen or a hundred statements each time we want to do something. That only works if functions don’t interfere with each other; if they do, we have to pay attention to the details once again, which quickly overloads our short-term memory.</p>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Following the call stack</h2>
</div>
<div class="panel-body">
<p>We previously wrote functions called <code>fence</code> and <code>outer</code>. Draw a diagram showing how the call stack changes when we run the following:</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="dt">print</span>(outer(fence(<span class="st">'carbon'</span>, <span class="st">'+'</span>)))</code></pre>
</div>
</section>
<h2 id="image-grids">Image Grids</h2>
<p>Let’s start by creating some simple heat maps of our own using a library called <code>ipythonblocks</code>. The first step is to create our own “image”:</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="ch">from</span> ipythonblocks <span class="ch">import</span> ImageGrid</code></pre>
<p>Unlike the <code>import</code> statements we have seen earlier, this one doesn’t load the entire <code>ipythonblocks</code> library. Instead, it just loads <code>ImageGrid</code> from that library, since that’s the only thing we need (for now).</p>
<p>Once we have <code>ImageGrid</code> loaded, we can use it to create a very simple grid of colored cells:</p>
<pre class="sourceCode python"><code class="sourceCode python">grid = ImageGrid(<span class="dv">5</span>, <span class="dv">3</span>)
grid.show()</code></pre>
<div class="figure">
<img src="img/grid-01.png" />
</div>
<p>Just like a NumPy array, an <code>ImageGrid</code> has some properties that hold information about it:</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="dt">print</span>(<span class="st">'grid width:'</span>, grid.width)
<span class="dt">print</span>(<span class="st">'grid height:'</span>, grid.height)
<span class="dt">print</span>(<span class="st">'grid lines on:'</span>, grid.lines_on)</code></pre>
<pre class="output"><code>grid width: 5
grid height: 3
grid lines on: True</code></pre>
<p>The obvious thing to do with a grid like this is color in its cells, but in order to do that, we need to know how computers represent color. The most common schemes are <a href="reference.html#rgb">RGB</a>, which is short for “red, green, blue”. RGB is an <a href="reference.html#additive-color-model">additive color model</a>: every shade is some combination of red, green, and blue intensities. We can think of these three values as being the axes in a cube:</p>
<div class="figure">
<img src="fig/color-cube.png" alt="RGB Color Cube" /><p class="caption">RGB Color Cube</p>
</div>
<p>An RGB color is an example of a multi-part value: like a Cartesian coordinate, it is one thing with several parts. We can represent such a value in Python using a <a href="reference.html#tuple">tuple</a>, which we write using parentheses instead of the square brackets used for a list:</p>
<pre class="sourceCode python"><code class="sourceCode python">position = (<span class="fl">12.3</span>, <span class="fl">45.6</span>)
<span class="dt">print</span>(<span class="st">'position is:'</span>, position)
color = (<span class="dv">10</span>, <span class="dv">20</span>, <span class="dv">30</span>)
<span class="dt">print</span>(<span class="st">'color is:'</span>, color)</code></pre>
<pre class="output"><code>position is: (12.3, 45.6)
color is: (10, 20, 30)</code></pre>
<p>We can select elements from tuples using indexing, just as we do with lists and arrays:</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="dt">print</span>(<span class="st">'first element of color is:'</span>, color[<span class="dv">0</span>])</code></pre>
<pre class="output"><code>first element of color is: 10</code></pre>
<p>Unlike lists and arrays, though, tuples cannot be changed after they are created — in technical terms, they are <a href="reference.html#immutable">immutable</a>:</p>
<pre class="sourceCode python"><code class="sourceCode python">color[<span class="dv">0</span>] = <span class="dv">40</span>
<span class="dt">print</span>(<span class="st">'first element of color after change:'</span>, color[<span class="dv">0</span>])</code></pre>
<pre class="error"><code>---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-11-9c3dd30a4e52> in <module>()
----> 1 color[0] = 40
2 print('first element of color after change:', color[0])
TypeError: 'tuple' object does not support item assignment</code></pre>
<p>If a tuple represents an RGB color, its red, green, and blue components can take on values between 0 and 255. The upper bound may seem odd, but it’s the largest number that can be represented in an 8-bit byte (i.e., 2<sup>8</sup>-1). This makes it easy for computers to manipulate colors, while providing fine enough gradations to fool most human eyes, most of the time.</p>
<p>Let’s see what a few RGB colors actually look like:</p>
<pre class="sourceCode python"><code class="sourceCode python">row = ImageGrid(<span class="dv">8</span>, <span class="dv">1</span>)
row[<span class="dv">0</span>, <span class="dv">0</span>] = (<span class="dv">0</span>, <span class="dv">0</span>, <span class="dv">0</span>) <span class="co"># no color => black</span>
row[<span class="dv">1</span>, <span class="dv">0</span>] = (<span class="dv">255</span>, <span class="dv">255</span>, <span class="dv">255</span>) <span class="co"># all colors => white</span>
row[<span class="dv">2</span>, <span class="dv">0</span>] = (<span class="dv">255</span>, <span class="dv">0</span>, <span class="dv">0</span>) <span class="co"># all red</span>
row[<span class="dv">3</span>, <span class="dv">0</span>] = (<span class="dv">0</span>, <span class="dv">255</span>, <span class="dv">0</span>) <span class="co"># all green</span>
row[<span class="dv">4</span>, <span class="dv">0</span>] = (<span class="dv">0</span>, <span class="dv">0</span>, <span class="dv">255</span>) <span class="co"># all blue</span>
row[<span class="dv">5</span>, <span class="dv">0</span>] = (<span class="dv">255</span>, <span class="dv">255</span>, <span class="dv">0</span>) <span class="co"># red and green</span>
row[<span class="dv">6</span>, <span class="dv">0</span>] = (<span class="dv">255</span>, <span class="dv">0</span>, <span class="dv">255</span>) <span class="co"># red and blue</span>
row[<span class="dv">7</span>, <span class="dv">0</span>] = (<span class="dv">0</span>, <span class="dv">255</span>, <span class="dv">255</span>) <span class="co"># green and blue</span>
row.show()</code></pre>
<div class="figure">
<img src="img/grid-02.png" />
</div>
<p>Simple color values like <code>(0,255,0)</code> are easy enough to decipher with a bit of practice, but what color is <code>(214,90,127)</code>? To help us, <code>ipythonblocks</code> provides a function called <code>show_color</code>:</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="ch">from</span> ipythonblocks <span class="ch">import</span> show_color
show_color(<span class="dv">214</span>, <span class="dv">90</span>, <span class="dv">127</span>)</code></pre>
<div class="figure">
<img src="fig/ipythonblocks_show_color_example.png" />
</div>
<p>It also provides a table of standard colors:</p>
<pre class="sourceCode python"><code class="sourceCode python"><span class="ch">from</span> ipythonblocks <span class="ch">import</span> colors
c = ImageGrid(<span class="dv">3</span>, <span class="dv">2</span>)
c[<span class="dv">0</span>, <span class="dv">0</span>] = colors[<span class="st">'Fuchsia'</span>]
c[<span class="dv">0</span>, <span class="dv">1</span>] = colors[<span class="st">'Salmon'</span>]
c[<span class="dv">1</span>, <span class="dv">0</span>] = colors[<span class="st">'Orchid'</span>]
c[<span class="dv">1</span>, <span class="dv">1</span>] = colors[<span class="st">'Lavender'</span>]
c[<span class="dv">2</span>, <span class="dv">0</span>] = colors[<span class="st">'LimeGreen'</span>]
c[<span class="dv">2</span>, <span class="dv">1</span>] = colors[<span class="st">'HotPink'</span>]
c.show()</code></pre>
<div class="figure">
<img src="img/grid-03.png" />
</div>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Making a colorbar</h2>
</div>
<div class="panel-body">
<p>Fill in the <code>____</code> in the code below to create a bar that changes color from dark blue to black.</p>
<pre class="sourceCode python"><code class="sourceCode python">bar = ImageGrid(<span class="dv">10</span>, <span class="dv">1</span>)
<span class="kw">for</span> x in <span class="dt">range</span>(<span class="dv">10</span>):
bar[x, <span class="dv">0</span>] = (<span class="dv">0</span>, <span class="dv">0</span>, ____)
bar.show()</code></pre>
</div>
</section>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Why RGB?</h2>
</div>
<div class="panel-body">
<p>Why do computers use red, green, and blue as their primary colors?</p>
</div>
</section>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Nested loops</h2>
</div>
<div class="panel-body">
<p>Will changing the nesting of the loops in the code above — i.e., wrapping the Y-axis loop around the X-axis loop — change the final image? Why or why not?</p>
</div>
</section>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Where to change data</h2>
</div>
<div class="panel-body">
<p>Why did we transpose our data outside our heat map function? Why not have the function perform the transpose?</p>
</div>
</section>
<section class="challenge panel panel-success">
<div class="panel-heading">
<h2><span class="glyphicon glyphicon-pencil"></span>Design choice: return versus display</h2>
</div>
<div class="panel-body">
<p>Why does the heat map function return the grid rather than displaying it immediately? Do you think this is a good or bad design choice?</p>
</div>
</section>
</div>
</div>
</article>
<div class="footer">
<a class="label swc-blue-bg" href="http://software-carpentry.org">Software Carpentry</a>
<a class="label swc-blue-bg" href="https://github.com/swcarpentry/python-novice-inflammation">Source</a>
<a class="label swc-blue-bg" href="mailto:[email protected]">Contact</a>
<a class="label swc-blue-bg" href="LICENSE.html">License</a>
</div>
</div>
<!-- Javascript placed at the end of the document so the pages load faster -->
<script src="http://software-carpentry.org/v5/js/jquery-1.9.1.min.js"></script>
<script src="css/bootstrap/bootstrap-js/bootstrap.js"></script>
</body>
</html>