201_oop_encapsulation.ipynb 28.4 KB
Newer Older
paugier's avatar
paugier committed
1
2
3
4
5
6
7
8
9
10
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
paugier's avatar
paugier committed
11
    "# Scientific computing course 2020\n",
paugier's avatar
paugier committed
12
    "\n",
paugier's avatar
paugier committed
13
    "**Acquire strong basis in Python to use it efficiently**\n",
paugier's avatar
paugier committed
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
    "\n",
    "Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTERRE), Christophe Picard (LJK), Loïc Huder (ISTerre)\n",
    "\n",
    "# Object-oriented programming: encapsulation\n",
    "\n",
    "Python is also an object-oriented language. Object-oriented programming is very useful and used in many libraries so it is very useful to understand how the simple object-oriented mechanisms work in Python."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "For some problems, Object-oriented programming is a very efficient paradigm. Many libraries use it so it is worth understanding what is object oriented programming (POO) and when it is useful.\n",
    "\n",
    "# Concepts\n",
    "\n",
    "## Object\n",
    "An object is an entity that has a state and a behavior. Objects are the basic elements of object-oriented system.\n",
    "\n",
    "## Class\n",
    "Classes are \"families\" of objects. A class is a pattern that describes how objects will be built."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## POO motivation: data encapsulation\n",
    "\n",
    "**Example: the weather stations**\n",
    "\n",
    "Let us suppose we have a set of weather stations that do measurements of wind speed and temperature. Suppose now one wants to compute some statistics on these data. A basic representation of a station will be an array of arrays: wind values and temperature values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "max temp is of 5°C at index 1 \n",
      "wind speed at max temp = 0 km/h\n"
     ]
    }
   ],
   "source": [
    "paris = [[10, 0, 20, 30, 20, 0], [1, 5, 1, -1, -1, 3]]\n",
    "\n",
    "# get wind when temperature is maximal\n",
    "idx_max_temp = paris[1].index(max(paris[1]))\n",
    "print(f\"max temp is of {paris[1][idx_max_temp]}°C at index {idx_max_temp} \")\n",
    "print(f\"wind speed at max temp = {paris[0][idx_max_temp]} km/h\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "**Comments on this solution**\n",
    "\n",
    "Many problems:\n",
    "\n",
    "- if the number of measurements increases (e.g. having rainfall, humidity, ...) the previous indexing will not be valid (what will paris[5] will represent? wind, temperature, ..., ?)\n",
    "- Code analysis is not (that) straightforward"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "**A possible solution: create a box**\n",
    "\n",
    "We can use a dictionnary:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "max temp is 5°C at index 1\n",
      "wind speed at max temp = 0 km/h\n"
     ]
    }
   ],
   "source": [
    "paris = {\"wind\": [10, 0, 20, 30, 20, 0], \"temperature\": [1, 5, 1, -1, -1, 3]}\n",
    "\n",
    "# get wind when temperature is minimal\n",
    "paris_temp = paris[\"temperature\"]\n",
    "idx_max_temp = paris_temp.index(max(paris_temp))\n",
    "\n",
    "print(f\"max temp is {paris_temp[idx_max_temp]}°C at index {idx_max_temp}\")\n",
    "print(f\"wind speed at max temp = {paris['wind'][idx_max_temp]} km/h\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "**Comments**\n",
    "- Pro\n",
    "  - More readable code (reading paris[\"temperature\"] is clearer than paris[1])\n",
    "  - Less error prone code (*i.e.* using words as keys allow to not use index numbers that are easily mistaken and lead to code that is hard to read and debug)\n",
    "  \n",
    "- Con \n",
    "  - The code to compute the final result is not very readable"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "**Improvement**\n",
    "\n",
    "Add functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "max temp is 5°C at index 1\n",
      "wind speed at max temp = 0 km/h\n"
     ]
    }
   ],
   "source": [
    "paris = {\"wind\": [10, 0, 20, 30, 20, 0], \"temperature\": [1, 5, 1, -1, -1, 3]}\n",
    "\n",
    "\n",
    "def max_temp(station):\n",
    "    \"\"\" returns the maximum temperature available in the station\"\"\"\n",
    "    return max(station[\"temperature\"])\n",
    "\n",
    "\n",
    "def arg_max_temp(station):\n",
    "    \"\"\" returns the index of maximum temperature available in the station\"\"\"\n",
    "    max_temperature = max_temp(station)\n",
    "    return station[\"temperature\"].index(max_temperature)\n",
    "\n",
    "\n",
    "idx_max_temp = arg_max_temp(paris)\n",
    "\n",
    "print(f\"max temp is {max_temp(paris)}°C at index {arg_max_temp(paris)}\")\n",
    "print(f\"wind speed at max temp = {paris['wind'][idx_max_temp]} km/h\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "test_arg_max_temp (__main__.TestWeatherStationDict0)\n",
      "test arg_max_temp computes correctly ... ok\n",
      "test_max_temp (__main__.TestWeatherStationDict0)\n",
      "test max_temp computes correctly ... ok\n",
      "\n",
      "----------------------------------------------------------------------\n",
      "Ran 2 tests in 0.002s\n",
      "\n",
      "OK\n"
     ]
    }
   ],
   "source": [
    "# testing\n",
    "import unittest\n",
    "\n",
    "\n",
    "class TestWeatherStationDict0(unittest.TestCase):\n",
    "    \"\"\"Test the weather station \"\"\"\n",
    "\n",
    "    def setUp(self):\n",
    "        \"\"\"Generates a well structured station (paris)\"\"\"\n",
    "        self.paris = {\n",
    "            \"wind\": [10, 0, 20, 30, 20, 0],\n",
    "            \"temperature\": [1, 5, 1, -1, -1, 3],\n",
    "        }\n",
    "\n",
    "    def test_max_temp(self):\n",
    "        \"\"\" test max_temp computes correctly\"\"\"\n",
    "        self.assertEqual(5, max_temp(self.paris))\n",
    "\n",
    "    def test_arg_max_temp(self):\n",
    "        \"\"\" test arg_max_temp computes correctly\"\"\"\n",
    "        self.assertEqual(1, arg_max_temp(self.paris))\n",
    "\n",
    "\n",
    "suite = unittest.TestLoader().loadTestsFromTestCase(TestWeatherStationDict0)\n",
    "_res = unittest.TextTestRunner(verbosity=2).run(suite)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "**Comments**\n",
    "\n",
    "- Pro:\n",
    "  - adding functions leads to a code that is easier to read (and therefore to debug!)\n",
    "  - testing functions can be done separately from the rest of the code\n",
    "- Con \n",
    "  - We rely on the fact that the dictionnaries have been built correctly (for example wind and temperature arrays have the same length)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "**Improvement**\n",
    "\n",
    "Define a function that builds the station (delegate the generation of the station dictionnary to a function)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "max temp is 5°C at index 1\n",
      "wind speed at max temp = 0 km/h\n"
     ]
    }
   ],
   "source": [
    "def build_station(wind, temp):\n",
    "    \"\"\" Build a station given wind and temp\n",
    "    :param wind: (list) floats of winds\n",
    "    :param temp: (list) float of temperatures\n",
    "    \"\"\"\n",
    "    if len(wind) != len(temp):\n",
    "        raise ValueError(\"wind and temperature should have the same size\")\n",
    "    return {\"wind\": list(wind), \"temperature\": list(temp)}\n",
    "\n",
    "\n",
    "def max_temp(station):\n",
    "    \"\"\" returns the maximum temperature available in the station\"\"\"\n",
    "    return max(station[\"temperature\"])\n",
    "\n",
    "\n",
    "def arg_max_temp(station):\n",
    "    \"\"\" returns the index of maximum temperature available in the station\"\"\"\n",
    "    max_temperature = max_temp(station)\n",
    "    return station[\"temperature\"].index(max_temperature)\n",
    "\n",
    "\n",
    "paris = build_station([10, 0, 20, 30, 20, 0], [1, 5, 1, -1, -1, 3])\n",
    "idx_max_temp = arg_max_temp(paris)\n",
    "\n",
    "print(f\"max temp is {max_temp(paris)}°C at index {arg_max_temp(paris)}\")\n",
    "print(f\"wind speed at max temp = {paris['wind'][idx_max_temp]} km/h\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "test_arg_max_temp (__main__.TestWeatherStationDict1)\n",
      "test arg_max_temp computs correctly ... ok\n",
      "test_build_station_with_iterable (__main__.TestWeatherStationDict1)\n",
      "Tests that the station can be generated from iterables ... ok\n",
      "test_max_temp (__main__.TestWeatherStationDict1)\n",
      "test max_temp computes conrrectly ... ok\n",
      "test_wrong_build (__main__.TestWeatherStationDict1)\n",
      "Tests that the station generation throws an error ... ok\n",
      "\n",
      "----------------------------------------------------------------------\n",
      "Ran 4 tests in 0.009s\n",
      "\n",
      "OK\n"
     ]
    }
   ],
   "source": [
    "# testing\n",
    "\n",
    "class TestWeatherStationDict1(unittest.TestCase):\n",
    "    \"\"\"Test the weather station \"\"\"\n",
    "\n",
    "    def setUp(self):\n",
    "        \"\"\"Generates a well structured station (paris)\"\"\"\n",
    "        self.paris = build_station([10, 0, 20, 30, 20, 0], [1, 5, 1, -1, -1, 3])\n",
    "\n",
    "    def test_build_station_with_iterable(self):\n",
    "        \"\"\" Tests that the station can be generated from iterables \"\"\"\n",
    "        station = build_station(range(10), range(10))\n",
    "        self.assertEqual(station[\"wind\"][0], 0)\n",
    "        self.assertEqual(station[\"wind\"][-1], 9)\n",
    "        self.assertEqual(station[\"temperature\"][0], 0)\n",
    "        self.assertEqual(station[\"temperature\"][-1], 9)\n",
    "\n",
    "    def test_wrong_build(self):\n",
    "        \"\"\" Tests that the station generation throws an error \n",
    "        if wind and temperature do not have the same size\"\"\"\n",
    "        with self.assertRaises(ValueError):\n",
    "            bad = build_station(range(10), range(4))\n",
    "\n",
    "    def test_max_temp(self):\n",
    "        \"\"\" test max_temp computes conrrectly\"\"\"\n",
    "        self.assertEqual(5, max_temp(self.paris))\n",
    "\n",
    "    def test_arg_max_temp(self):\n",
    "        \"\"\" test arg_max_temp computs correctly\"\"\"\n",
    "        self.assertEqual(1, arg_max_temp(self.paris))\n",
    "\n",
    "\n",
    "suite = unittest.TestLoader().loadTestsFromTestCase(TestWeatherStationDict1)\n",
    "_res = unittest.TextTestRunner(verbosity=2).run(suite)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "**Comments**\n",
    "\n",
    "  - If the dedicated function `build_station` is used, the returned dictionary is well structured.\n",
    "  - If one changes `build_station`, only `max_temp` and `arg_max_temp` have to be changed accordingly"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Object oriented in a nutshell\n",
    "\n",
    "A class defines a template used for building object. \n",
    "In our example, the class (named `WeatherStation`) defines the specifications of what is a weather station (*i.e*, a weather station should contain an array for wind speeds, named \"wind\", and an array for temperatures, named \"temp\").\n",
    "`paris` should now be an object that answers to these specifications. Is is called an **instance** of the class `WeatherStation`.\n",
    "\n",
    "When defining the class, we need to define how to build it (special \"function\" `__init__`). \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "max temp is 5°C at index 1\n",
      "wind speed at max temp = 0 km/h\n"
     ]
    }
   ],
   "source": [
    "class WeatherStation(object):\n",
    "    \"\"\" A weather station that holds wind and temperature\n",
    "    \n",
    "    :param wind: any ordered iterable\n",
    "    :param temperature: any ordered iterable\n",
    "    \n",
    "    wind and temperature must have the same length.\n",
    "    \n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, wind, temperature):\n",
    "        self.wind = list(wind)\n",
    "        self.temp = list(temperature)\n",
    "        if len(self.wind) != len(self.temp):\n",
    "            raise ValueError(\n",
    "                \"wind and temperature should have the same size\"\n",
    "            )\n",
    "\n",
    "    def max_temp(self):\n",
    "        \"\"\" returns the maximum temperature recorded in the station\"\"\"\n",
    "        return max(self.temp)\n",
    "\n",
    "    def arg_max_temp(self):\n",
    "        \"\"\" returns the index of (one of the) maximum temperature recorded in the station\"\"\"\n",
    "        return self.temp.index(self.max_temp())\n",
    "\n",
    "\n",
    "paris = WeatherStation([10, 0, 20, 30, 20, 0], [1, 5, 1, -1, -1, 3])\n",
    "# OR paris = WeatherStation(wind=[10, 0, 20, 30, 20, 0], temperature=[1, 5, 1, -1, -1, 3])\n",
    "idx_max_temp = paris.arg_max_temp()\n",
    "\n",
    "print(f\"max temp is {paris.max_temp()}°C at index {paris.arg_max_temp()}\")\n",
    "print(f\"wind speed at max temp = {paris.wind[idx_max_temp]} km/h\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "**Comments**\n",
    "\n",
    "The `max_temp` and the `arg_max_temp` are now part of the class `WeatherStation`. Functions attached to classes are named **methods**.\n",
    "Similary, `wind` and `temp` lists are also now part this class. Variables attached to classes are named **members** or **attributes**.\n",
    "\n",
    "An object (here `paris`) thus contains both *attributes* (holding data for example) and *methods* to access and/or process the data.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "subslide"
    }
   },
   "source": [
    "**Testing** "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "test_arg_max_temp (__main__.TestWeatherStation)\n",
      "test arg_max_temp function ... ok\n",
      "test_building_with_bad_arrays (__main__.TestWeatherStation)\n",
      "test that an exception is raised with incorrect inputs ... ok\n",
      "test_building_with_good_input_arrays (__main__.TestWeatherStation)\n",
      "test that things goes smoothly if the input are correct ... ok\n",
      "test_building_with_input_iterables (__main__.TestWeatherStation)\n",
      "test that things goes smoothly if the input are correct ... ok\n",
      "test_max_temp (__main__.TestWeatherStation)\n",
      "test test_max_temp function ... ok\n",
      "\n",
      "----------------------------------------------------------------------\n",
      "Ran 5 tests in 0.009s\n",
      "\n",
      "OK\n"
     ]
    }
   ],
   "source": [
    "class TestWeatherStation(unittest.TestCase):\n",
    "    \"\"\"Test the weather station \"\"\"\n",
    "\n",
    "    def setUp(self):\n",
    "        \"\"\"Generates a well structured station (paris)\"\"\"\n",
    "        self.paris = WeatherStation(\n",
    "            [10, 0, 20, 30, 20, 0], \n",
    "            [1, 5, 1, -1, -1, 3],\n",
    "        )\n",
    "\n",
    "    def test_building_with_good_input_arrays(self):\n",
    "        \"\"\" test that things goes smoothly if the input are correct\"\"\"\n",
    "        self.assertEqual(0, self.paris.wind[1])\n",
    "        self.assertEqual(5, self.paris.temp[1])\n",
    "\n",
    "    def test_building_with_input_iterables(self):\n",
    "        \"\"\" test that things goes smoothly if the input are correct\"\"\"\n",
    "        r_station = WeatherStation(range(10), range(10))\n",
    "        self.assertEqual(4, r_station.wind[4])\n",
    "        self.assertEqual(5, r_station.temp[5])\n",
    "\n",
    "    def test_building_with_bad_arrays(self):\n",
    "        \"\"\" test that an exception is raised with incorrect inputs\"\"\"\n",
    "        with self.assertRaises(ValueError):\n",
    "            bad_station = WeatherStation([10, 0, 20, 30, 20, 0], [1, 5, 1])\n",
    "\n",
    "    def test_max_temp(self):\n",
    "        \"\"\" test test_max_temp function\"\"\"\n",
    "        self.assertEqual(5, self.paris.max_temp())\n",
    "\n",
    "    def test_arg_max_temp(self):\n",
    "        \"\"\" test arg_max_temp function\"\"\"\n",
    "        self.assertEqual(1, self.paris.arg_max_temp())\n",
    "\n",
    "\n",
    "suite = unittest.TestLoader().loadTestsFromTestCase(TestWeatherStation)\n",
    "_res = unittest.TextTestRunner(verbosity=2).run(suite)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "## Do It Yourself (advanced)\n",
    "\n",
    "- Add a method (`perceived_temp`) that takes as input a temperature and wind and return the perceived temperature, i.e. taking into account the wind chill effect.\n",
    "- Modify `max_temp` and `arg_max_temp` so that they take an additional optional boolean parameter (*e.g.* perceived default to False). If `perceived` is False, the methods have the same behaviour as before. If perceived is True, the temperatures to process are the perceived temperatures.\n",
    "- Code so that all the tests are passing.\n",
    "- Add a tests for a method (`perceived_temperatures`) that returns an array containing all the perceived temperatures.\n",
    "- Code the method `perceived_temperatures` so that all tests are passing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "test_arg_max_temp_no_perceived (__main__.TestWeatherStation)\n",
      "test arg_max_temp function ... ok\n",
      "test_building_with_bad_arrays (__main__.TestWeatherStation)\n",
      "test exception is raised with bad entry ... ok\n",
      "test_building_with_good_input_arrays (__main__.TestWeatherStation)\n",
      "test things goes smoothly if input are correct ... ok\n",
      "test_building_with_input_iterables (__main__.TestWeatherStation)\n",
      "test things goes smoothly if input are correct ... ok\n",
      "test_max_temp_no_perceived (__main__.TestWeatherStation)\n",
      "test max temp function ... ok\n",
      "test_max_temp_perceived (__main__.TestWeatherStation)\n",
      "test max temp function ... ok\n",
      "test_perceived (__main__.TestWeatherStation)\n",
      "test that the perceived temp is lower than the regular temp with wind ... ok\n",
      "test_perceived_temperatures (__main__.TestWeatherStation)\n",
      "test that the perceived temperatures generation works ... ok\n",
      "test_perceived_with_null_wind (__main__.TestWeatherStation)\n",
      "test that the perceived temp is the same without wind ... ok\n",
      "\n",
      "----------------------------------------------------------------------\n",
      "Ran 9 tests in 0.014s\n",
      "\n",
      "OK\n"
     ]
    }
   ],
   "source": [
    "class WeatherStation(object):\n",
    "    \"\"\" A weather station that holds wind and temperature \"\"\"\n",
    "\n",
    "    def __init__(self, wind, temperature):\n",
    "        \"\"\" initialize the weather station. \n",
    "        Precondition: wind and temperature must have the same length\n",
    "        :param wind: any ordered iterable\n",
    "        :param temperature: any ordered iterable\"\"\"\n",
    "        self.wind = list(wind)\n",
    "        self.temp = list(temperature)\n",
    "        if len(self.wind) != len(self.temp):\n",
    "            raise ValueError(\n",
    "                \"wind and temperature should have the same size\"\n",
    "            )\n",
    "\n",
    "    def perceived_temp(self, index):\n",
    "        \"\"\" computes the perceived temp according to \n",
    "        https://en.wikipedia.org/wiki/Wind_chill\n",
    "        i.e. The standard Wind Chill formula for Environment Canada is: \n",
    "        apparent = 13.12 + 0.6215*air_temp - 11.37*wind_speed^0.16 + 0.3965*air_temp*wind_speed^0.16\n",
    "        \n",
    "        :param index: the index for which the computation must be made\n",
    "        :return: the perceived temperature\"\"\"\n",
    "        air_temp = self.temp[index]\n",
    "        wind_speed = self.wind[index]\n",
    "        # Perceived temperature does not have a sense without wind...\n",
    "        if wind_speed == 0:\n",
    "            apparent_temp = air_temp\n",
    "        else:\n",
    "            apparent_temp = 13.12 + 0.6215*air_temp \\\n",
    "                            - 11.37*wind_speed**0.16 \\\n",
    "                            + 0.3965*air_temp*wind_speed**0.16\n",
    "        # Let's round to avoid trailing decimals...\n",
    "        return round(apparent_temp, 2)\n",
    "    \n",
    "    def perceived_temperatures(self):\n",
    "        \"\"\" Returns an array of percieved temp computed from the temperatures and wind speed data \"\"\"\n",
    "        apparent_temps = []\n",
    "        for index in range(len(self.wind)):\n",
    "            # Reusing the method perceived_temp defined above\n",
    "            apparent_temperature = self.perceived_temp(index)\n",
    "            apparent_temps.append(apparent_temperature)\n",
    "        return apparent_temps\n",
    "\n",
    "    def max_temp(self, perceived=False):\n",
    "        \"\"\" returns the maximum temperature record in the station\"\"\"\n",
    "        if perceived:\n",
    "            apparent_temp = self.perceived_temperatures()\n",
    "            return max(apparent_temp)\n",
    "        else:\n",
    "            return max(self.temp)\n",
    "\n",
    "    def arg_max_temp(self, perceived=False):\n",
    "        \"\"\" returns the index of (one of the) maximum temperature record in the station\"\"\"\n",
    "        if perceived:\n",
    "            temp_array_to_search = self.perceived_temperatures()\n",
    "        else:\n",
    "            temp_array_to_search = self.temp\n",
    "        return temp_array_to_search.index(self.max_temp(perceived))\n",
    "\n",
    "\n",
    "class TestWeatherStation(unittest.TestCase):\n",
    "    \"\"\"Test the weather station \"\"\"\n",
    "\n",
    "    def setUp(self):\n",
    "        \"\"\"Generates a well formed station (paris)\"\"\"\n",
    "        self.paris = WeatherStation(\n",
    "            [10, 50, 20, 30, 20, 0],\n",
    "            [1, 5, 1, -1, -1, 3],\n",
    "        )\n",
    "\n",
    "    def test_building_with_good_input_arrays(self):\n",
    "        \"\"\" test things goes smoothly if input are correct\"\"\"\n",
    "        self.assertEqual(50, self.paris.wind[1])\n",
    "        self.assertEqual(5, self.paris.temp[1])\n",
    "\n",
    "    def test_building_with_input_iterables(self):\n",
    "        \"\"\" test things goes smoothly if input are correct\"\"\"\n",
    "        r_station = WeatherStation(range(10), range(10))\n",
    "        self.assertEqual(4, r_station.wind[4])\n",
    "        self.assertEqual(5, r_station.temp[5])\n",
    "\n",
    "    def test_building_with_bad_arrays(self):\n",
    "        \"\"\" test exception is raised with bad entry\"\"\"\n",
    "        with self.assertRaises(ValueError):\n",
    "            bad_station = WeatherStation([10, 50, 20, 30, 20, 0], [1, 5, 1])\n",
    "            \n",
    "    def test_perceived_with_null_wind(self):\n",
    "        \"\"\" test that the perceived temp is the same without wind\"\"\"\n",
    "        index = 5\n",
    "        assert self.paris.wind[index] == 0\n",
    "        self.assertEqual(self.paris.temp[index], self.paris.perceived_temp(index))\n",
    "\n",
    "    def test_perceived(self):\n",
    "        \"\"\" test that the perceived temp is lower than the regular temp with wind \"\"\"\n",
    "        index = 2\n",
    "        assert self.paris.wind[index] > 0\n",
    "        self.assertTrue(self.paris.perceived_temp(index) < self.paris.temp[index])\n",
    "        \n",
    "    def test_perceived_temperatures(self):\n",
    "        \"\"\" test that the perceived temperatures generation works\"\"\"\n",
    "        apparent_temps = self.paris.perceived_temperatures()\n",
    "        self.assertTrue(isinstance(apparent_temps, list))\n",
    "        self.assertEqual(len(apparent_temps), len(self.paris.temp))\n",
    "        for i in range(0, len(apparent_temps)):\n",
    "            self.assertLessEqual(apparent_temps[i], self.paris.temp[i])\n",
    "\n",
    "    def test_max_temp_no_perceived(self):\n",
    "        \"\"\" test max temp function \"\"\"\n",
    "        self.assertEqual(5, self.paris.max_temp())\n",
    "\n",
    "    def test_arg_max_temp_no_perceived(self):\n",
    "        \"\"\" test arg_max_temp function\"\"\"\n",
    "        self.assertEqual(1, self.paris.arg_max_temp())\n",
    "        \n",
    "    def test_max_temp_perceived(self):\n",
    "        \"\"\" test max temp function\"\"\"\n",
    "        self.assertEqual(3, self.paris.max_temp(perceived=True))\n",
    "\n",
    "    def test_arg_max_temp_no_perceived(self):\n",
    "        \"\"\" test arg_max_temp function\"\"\"\n",
    "        self.assertEqual(5, self.paris.arg_max_temp(perceived=True))\n",
    "\n",
    "\n",
    "suite = unittest.TestLoader().loadTestsFromTestCase(TestWeatherStation)\n",
    "_res = unittest.TextTestRunner(verbosity=2).run(suite)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Comments :\n",
    "- The wind array was changed to have different maximum temperatures for the air and perceived temperatures : for air temperatures, the max is 5°C (with a wind speed 50 km/h). For perceived temperatures, the max is 3°C (as the wind speed is 0).\n",
    "- It was a choice to set the apparent/perceived temperature to the air temperature if the wind speed is 0 so the tests were written with this in mind. Testing such choices allows to have clear inputs/outputs.\n",
    "- `isinstance` allows to test the type of an object (in this case, we test if `apparent_temps` is a list)\n",
    "- When testing boolean in if structures: use `if perceived:` rather than `if perceived == True:`. It is equivalent but clearer and shorter !\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "\n",
    "## Coming next\n",
    "\n",
    "What if we now have a weather station that also measure humidity ?\n",
    "\n",
    "Do we need to rewrite everything ? \n",
    "\n",
    "What if we rewrite everything and we find a bug ? \n",
    "\n",
    "**Here comes inheritance**"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
paugier's avatar
paugier committed
791
   "version": "3.8.2"
paugier's avatar
paugier committed
792
793
794
  }
 },
 "nbformat": 4,
paugier's avatar
paugier committed
795
 "nbformat_minor": 4
paugier's avatar
paugier committed
796
}