-
Notifications
You must be signed in to change notification settings - Fork 0
/
More Python.ipynb
826 lines (826 loc) · 27.6 KB
/
More Python.ipynb
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
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# More Python"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Object-oriented Python"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We're going to explore Python's system for \"object-oriented programming\". Object-oriented programming is a way of combining functions with data. In fact, you've already used it. When you created a `list`, you were creating an **object** of the `list` **class**. When you reversed the list, you used the `reverse` **method** of the `list` class. A method is just a function which is attached to a class. So, in Python, lists are objects. Numbers, strings, and dictionaries are objects too. Functions are also objects! Almost everything in Python is an object.\n",
"\n",
"As well as using built in classes, you can create your own. Classes are a good way of organising your code. It helps you to keep related code together. This will be helpful if someone else ever has to read it. It will also be helpful when you read it in a year's time.\n",
"\n",
"The best way to understand this is to look at an example. We will be using object oriented programming to build a taxonomic tree."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Basic Class"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Suppose that we want to build a taxonomic tree for part of the Pythonidae family of snakes. \n",
"\n",
"![Tree 1](images/tree_1.png)\n",
"\n",
"Each taxa in the tree has two basic attributes: Its name, and its parent taxon. We can build a class which models this, as follows:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"class Taxon(object):\n",
" def __init__(self, name, parent):\n",
" self.name = name\n",
" self.parent = parent"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"There will be several things here that are new, so we will go through them one at a time. Class definitions look very similar to function definitions. Instead of using `def`, we use `class` followed by the new class' name. In parenthesis after the name is the class that we want this class to **inherit** from. We don't need to use inheritance for this class, so we'll just inherit from the base class in Python which is `object`.\n",
"\n",
"Following the class definition line, we can define methods. Just as the lines of code which belong to a method are indented, the methods which belong to a class are indented.\n",
"\n",
"The `__init__` method is a special method which is run each time an object is created. The `__init__` method is used to set up the object. The main thing which distinguishes a method from a class is that the first argument to a method is always `self`. `self` is used to access the methods and attributes which belong to the object. In this case, we want to save the `name` and `parent` of the taxon. We do this by creating an attribute for each of these. Attributes are accessed using **`.`**. They are created by assigning a value to them.\n",
"\n",
"How do we use this new class? Let's create part of the Pythonidae taxonomy:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"pythonidae = Taxon(\"Pythonidae\", None)\n",
"python = Taxon(\"Python\", pythonidae)\n",
"burmese_python = Taxon(\"Python bivittatus\", python)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To create an object of a particular class, we use the name of the class, as if we were calling a function with the class' name. You've seen this before, when you used the `list`, `str` and `int` functions to create lists and strings and integers. When you create a new object, Python calls the `__init__` method. It automatically fills in the value of the `self` argument.\n",
"\n",
"When I created the `Taxon` object for Pythonidae, instead of giving a parent taxon, I used `None`. `None` in Python is a special value which is used to represent the concept of nothing. In this case, I don't want to give Pythonidae a parent taxon, so I use `None`.\n",
"\n",
"The attributes which are assigned in the `__init__` method can be accessed after the object's creation, using **`.`**:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Python bivittatus'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"burmese_python.name"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Task 1\n",
"\n",
"Suppose that we want to record the rank of the taxa. How could you modify the ``__init__`` method to support this?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Methods\n",
"\n",
"An obvious task with a taxonomic tree is to find the ancestors of a particular taxon. With object-oriented programming, we can write a method which will do this. We will modify our previous `Taxon` class to add this method."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"class Taxon(object):\n",
" def __init__(self, name, parent):\n",
" self.name = name\n",
" self.parent = parent\n",
" \n",
" def ancestors(self):\n",
" current_taxon = self.parent\n",
" ancestors = []\n",
" while current_taxon is not None:\n",
" ancestors.append(current_taxon)\n",
" current_taxon = current_taxon.parent\n",
" return ancestors\n",
" \n",
"pythonidae = Taxon(\"Pythonidae\", None)\n",
"python = Taxon(\"Python\", pythonidae)\n",
"burmese_python = Taxon(\"Python bivittatus\", python)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The `ancestors` method doesn't take any arguments, apart from the automatic `self` variable. The output of the method should be a list of taxa. The parent taxon of the taxon on which the method is being called should be the first element on the list. More distant ancestors should follow. To create this list, we first create an empty list `ancestors = []`. We then use a `while` loop to add to it. A `while` loop is like a `for` loop, but instead of running the loop body once for each element in a `range` or `list`, the body is repeatedly run until the `while` condition is no longer true. In the loop body, the value of the `current_taxon` variable is appended to the ancestors list. The `current_taxon` variable is then set to the parent of the existing `current_taxon`. Remember that we set the value of the Pythonidae taxon's parent to be `None`. When this value is assigend to `current_taxon`, the expression `current_taxon is not None` is no longer true. This means that the loop stops running.\n",
"\n",
"We can use the new method to find the taxa which the Burmese Python belongs to:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<__main__.Taxon at 0x1075b2b00>, <__main__.Taxon at 0x1075b2b38>]"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"burmese_python.ancestors()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This output isn't very helpful. We can use a `for` loop to print out the names of the ancestors:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Python\n",
"Pythonidae\n"
]
}
],
"source": [
"for ancestor in burmese_python.ancestors():\n",
" print(ancestor.name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Iterables"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In Python, an `iterable` is an object which can be iterated over. In other words, it can be used in a `for` loop. You have seen that a `list` is an iterable. A ``range`` is also an iterable. You can create your own iterables, which can help simplify your code, and make it more efficient. We can rewrite the ancestors method to return an `iterable` instead of a `list`:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"class Taxon(object):\n",
" def __init__(self, name, parent):\n",
" self.name = name\n",
" self.parent = parent\n",
" \n",
" def ancestors(self):\n",
" current_taxon = self.parent\n",
" while current_taxon is not None:\n",
" yield current_taxon\n",
" current_taxon = current_taxon.parent\n",
" \n",
"pythonidae = Taxon(\"Pythonidae\", None)\n",
"python = Taxon(\"Python\", pythonidae)\n",
"burmese_python = Taxon(\"Python bivittatus\", python)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Written this way, the `ancestors` list is not needed. Instead of appending to a `list`, we use `yield` to say a particular value should be included in the iteration. Written this way, the method is shorter, and easier to understand. The `for` loop works just as before:"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Python\n",
"Pythonidae\n"
]
}
],
"source": [
"for ancestor in burmese_python.ancestors():\n",
" print(ancestor.name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we do want a list of ancestors, we can use the `list` function:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[<__main__.Taxon at 0x1075b2908>, <__main__.Taxon at 0x1074d44e0>]"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list(burmese_python.ancestors())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Question\n",
"Using an `iterable` has another big advantage over returning a lists. What is it? This advantage is very important when iterating over very large things."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Task 2\n",
"\n",
"Instead of printing out the names of the taxa which the Burmese Python belongs to, how could you construct a `list` containing the names?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## List Comprehensions\n",
"\n",
"Python has a shortcut for building lists that are derived from `iterable` objects called **list comprehension**. The previous task can be completed very easily using a list comprehension:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Python', 'Pythonidae']"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[ancestor.name for ancestor in burmese_python.ancestors()]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The right hand side of the list comprehension looks just like the `for` loop we've used before. On the left, before the `for`, is the statement which is used to build the list. "
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"pythonidae = Taxon(\"Pythonidae\", None)\n",
"python = Taxon(\"Python\", pythonidae)\n",
"burmese_python = Taxon(\"Python bivittatus\", python)\n",
"ball_python = Taxon(\"Python regius\", python)\n",
"reticulated_python = Taxon(\"Python reticulatus\", python)"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Python', 'Pythonidae']"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[a.name for a in ball_python.ancestors()]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Printing a tree\n",
"\n",
"![Tree 2](images/tree_2.png)\n",
"\n",
"It would be useful to be able to print out a version of the tree. For example, as follows:\n",
"\n",
" Pythonidae\n",
" +--- Morelia\n",
" +--- Morelia spilota\n",
" +--- Python\n",
" +--- Python reticulatus\n",
" Python regius\n",
" Python bivittatus\n",
" \n",
"To facilitate this, we need the taxa to \"know\" what their child taxa are. We can do this by modifying the `__init__` method. When a tax is created, it should append itself to its parent's list of children."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [],
"source": [
"class Taxon(object):\n",
" def __init__(self, name, parent):\n",
" self.name = name\n",
" self.parent = parent\n",
" self.children = []\n",
" if self.parent is not None:\n",
" self.parent.children.append(self)\n",
" \n",
" def ancestors(self):\n",
" current_taxon = self\n",
" while current_taxon is not None:\n",
" yield current_taxon\n",
" current_taxon = current_taxon.parent"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [],
"source": [
"pythonidae = Taxon(\"Pythonidae\", None)\n",
"python = Taxon(\"Python\", pythonidae)\n",
"burmese_python = Taxon(\"Python bivittatus\", python)\n",
"ball_python = Taxon(\"Python regius\", python)\n",
"reticulated_python = Taxon(\"Python reticulatus\", python)\n",
"tree_python = Taxon(\"Morelia\", pythonidae)\n",
"carpet_python = Taxon(\"Morelia spilota\", tree_python)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Python bivittatus', 'Python regius', 'Python reticulatus']"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[c.name for c in python.children]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, we can write an iterable method which yields the descendents of the current node."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [],
"source": [
"class Taxon(object):\n",
" def __init__(self, name, parent):\n",
" self.name = name\n",
" self.parent = parent\n",
" self.children = []\n",
" if self.parent is not None:\n",
" self.parent.children.append(self)\n",
" \n",
" def ancestors(self):\n",
" current_taxon = self\n",
" while current_taxon is not None:\n",
" yield current_taxon\n",
" current_taxon = current_taxon.parent\n",
" \n",
" def descendents(self):\n",
" remaining_taxons = [self]\n",
" while len(remaining_taxons) > 0:\n",
" current_taxon = remaining_taxons.pop()\n",
" if current_taxon is not self:\n",
" yield current_taxon\n",
" remaining_taxons.extend(current_taxon.children)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"pythonidae = Taxon(\"Pythonidae\", None)\n",
"python = Taxon(\"Python\", pythonidae)\n",
"burmese_python = Taxon(\"Python bivittatus\", python)\n",
"ball_python = Taxon(\"Python regius\", python)\n",
"reticulated_python = Taxon(\"Python reticulatus\", python)\n",
"tree_python = Taxon(\"Morelia\", pythonidae)\n",
"carpet_python = Taxon(\"Morelia spilota\", tree_python)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Morelia',\n",
" 'Morelia spilota',\n",
" 'Python',\n",
" 'Python reticulatus',\n",
" 'Python regius',\n",
" 'Python bivittatus']"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[d.name for d in pythonidae.descendents()]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Task 3\n",
"\n",
"Write a method for printing out a tree. If called on the Pythonidae taxon object, it should print out the entire tree of Pythons. You can use the `descendents` method to help you write it. You can recreate the visualisation below, or do it any other way you wish.\n",
"\n",
" * Pythonidae\n",
" +--- Morelia\n",
" +--- Morelia spilota\n",
" +--- Python\n",
" +--- Python reticulatus\n",
" +--- Python regius\n",
" +--- Python bivittatus"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using APIs\n",
"It's very common to want to fetch data from the Internet, and process it in a Python program. Many modern websites include APIs (Application programming interface), which make this task easier. Web pages are intended for humans to read and understand, whereas APIs provide the same data, but in a format that is easier for computers to read and process. At the EBI, many different services are provided through an API. The Ensembl project provides an API for retrieving taxonomic information.\n",
"\n",
"To retrieve information over the Internet, we will use the `requests` package. This should already be installed on your virtual machine. If not, run:\n",
"\n",
" conda install requests\n",
" \n",
"Before starting, we should read [the API documentation](https://rest.ensembl.org/documentation/info/taxonomy_classification). We can see that in order to get the taxonomic information for *Python reticulatus* we should access the following URL:\n",
"\n",
" https://rest.ensembl.org/taxonomy/id/Python%20reticulatus?content-type=application/json\n",
" \n",
"If you visit this URL, you should see the following:\n",
"\n",
" {\"scientific_name\":\"Malayopython reticulatus\",\"parent\":{\"scientific_name\":\"Malayopython\",\"name\":\"Malayopython\",\"id\":\"1496304\",\"tags\":{\"scientific name\":[\"Malayopython\"],\"synonym\":[\"Broghammerus\"],\"name\":[\"Malayopython\"],\"merged_taxon_id\":[\"1334238\"],\"authority\":[\"Broghammerus Hoser, 2004\"]},\"leaf\":0},\"name\":\"Malayopython reticulatus\",\"children\":[{\"scientific_name\":\"Malayopython reticulatus jampeanus\",\"name\":\"Malayopython reticulatus jampeanus\",\"id\":\"147707\",\"tags\":{\"scientific name\":[\"Malayopython reticulatus jampeanus\"],\"synonym\":[\"Broghammerus reticulatus jampeanus\",\"Python reticulatus jampeanus\"],\"name\":[\"Malayopython reticulatus jampeanus\"],\"authority\":[\"Python reticulatus jampeanus Auliya et al., 2002\"]},\"leaf\":1},{\"scientific_name\":\"Malayopython reticulatus saputrai\",\"name\":\"Malayopython reticulatus saputrai\",\"id\":\"147708\",\"tags\":{\"scientific name\":[\"Malayopython reticulatus saputrai\"],\"synonym\":[\"Broghammerus reticulatus saputrai\",\"Python reticulatus saputrai\"],\"name\":[\"Malayopython reticulatus saputrai\"],\"authority\":[\"Python reticulatus saputrai Auliya et al., 2002\"]},\"leaf\":1}],\"id\":\"1496311\",\"tags\":{\"scientific name\":[\"Malayopython reticulatus\"],\"synonym\":[\"Boa reticulata\",\"Broghammerus reticulatus\",\"Python reticulatus\"],\"genbank common name\":[\"reticulated python\"],\"name\":[\"Malayopython reticulatus\"],\"common name\":[\"reticulate python\"],\"merged_taxon_id\":[\"37580\"],\"authority\":[\"Python reticulatus (Schneider, 1801)\"]},\"leaf\":0}\n",
" \n",
"This is **JSON** form at data. JSON is a format for supplying data in dictionary and list format. Many different programming langugages can use data in this format. The `requests` package can automatically convert it into Python data types"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"python_request = requests.get(\"https://rest.ensembl.org/taxonomy/id/Pythonidae?content-type=application/json\")"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"python_json = python_request.json()"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'children': [{'id': '51894',\n",
" 'leaf': 0,\n",
" 'name': 'Morelia',\n",
" 'scientific_name': 'Morelia',\n",
" 'tags': {'name': ['Morelia'],\n",
" 'scientific name': ['Morelia'],\n",
" 'synonym': ['Chondropython']}},\n",
" {'id': '37579',\n",
" 'leaf': 0,\n",
" 'name': 'Python',\n",
" 'scientific_name': 'Python',\n",
" 'tags': {'merged_taxon_id': ['51884'],\n",
" 'name': ['Python'],\n",
" 'scientific name': ['Python']}},\n",
" {'id': '196249',\n",
" 'leaf': 0,\n",
" 'name': 'Antaresia',\n",
" 'scientific_name': 'Antaresia',\n",
" 'tags': {'name': ['Antaresia'], 'scientific name': ['Antaresia']}},\n",
" {'id': '1496304',\n",
" 'leaf': 0,\n",
" 'name': 'Malayopython',\n",
" 'scientific_name': 'Malayopython',\n",
" 'tags': {'authority': ['Broghammerus Hoser, 2004'],\n",
" 'merged_taxon_id': ['1334238'],\n",
" 'name': ['Malayopython'],\n",
" 'scientific name': ['Malayopython'],\n",
" 'synonym': ['Broghammerus']}},\n",
" {'id': '51886',\n",
" 'leaf': 0,\n",
" 'name': 'Liasis',\n",
" 'scientific_name': 'Liasis',\n",
" 'tags': {'merged_taxon_id': ['129309'],\n",
" 'name': ['Liasis'],\n",
" 'scientific name': ['Liasis'],\n",
" 'synonym': ['Apodora']}},\n",
" {'id': '51882',\n",
" 'leaf': 0,\n",
" 'name': 'Aspidites',\n",
" 'scientific_name': 'Aspidites',\n",
" 'tags': {'name': ['Aspidites'], 'scientific name': ['Aspidites']}},\n",
" {'id': '1497996',\n",
" 'leaf': 0,\n",
" 'name': 'Simalia',\n",
" 'scientific_name': 'Simalia',\n",
" 'tags': {'name': ['Simalia'], 'scientific name': ['Simalia']}},\n",
" {'id': '461340',\n",
" 'leaf': 0,\n",
" 'name': 'Bothrochilus',\n",
" 'scientific_name': 'Bothrochilus',\n",
" 'tags': {'merged_taxon_id': ['129325'],\n",
" 'name': ['Bothrochilus'],\n",
" 'scientific name': ['Bothrochilus'],\n",
" 'synonym': ['Leiopython']}}],\n",
" 'id': '34984',\n",
" 'leaf': 0,\n",
" 'name': 'Pythonidae',\n",
" 'parent': {'id': '34979',\n",
" 'leaf': 0,\n",
" 'name': 'Henophidia',\n",
" 'scientific_name': 'Henophidia',\n",
" 'tags': {'name': ['Henophidia'],\n",
" 'scientific name': ['Henophidia'],\n",
" 'synonym': ['Boidea', 'Booidea']}},\n",
" 'scientific_name': 'Pythonidae',\n",
" 'tags': {'genbank common name': ['true pythons'],\n",
" 'merged_taxon_id': ['196246'],\n",
" 'name': ['Pythonidae'],\n",
" 'scientific name': ['Pythonidae'],\n",
" 'synonym': ['Pythoninae']}}"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"python_json"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Pythonidae\n"
]
}
],
"source": [
"print(python_json[\"name\"])"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Morelia\n",
"Python\n",
"Antaresia\n",
"Malayopython\n",
"Liasis\n",
"Aspidites\n",
"Simalia\n",
"Bothrochilus\n"
]
}
],
"source": [
"for child in python_json[\"children\"]:\n",
" print(child[\"name\"])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can see that instead of accessing attributes using **`.`**, this data is a in dictionry, so we access it using the key name syntax. We could populate the data in the `Taxon` class by fetching it over the internet:"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"class Taxon(object):\n",
" def __init__(self, name, parent):\n",
" taxon_data = requests.get(\"https://rest.ensembl.org/taxonomy/id/\" + name + \"?content-type=application/json\").json()\n",
" self.name = taxon_data[\"name\"]\n",
" self.parent = parent\n",
" self.children = []\n",
" \n",
" def ancestors(self):\n",
" current_taxon = self\n",
" while current_taxon is not None:\n",
" yield current_taxon\n",
" current_taxon = current_taxon.parent\n",
" \n",
" def descendents(self):\n",
" remaining_taxons = [self]\n",
" while len(remaining_taxons) > 0:\n",
" current_taxon = remaining_taxons.pop()\n",
" if current_taxon is not self:\n",
" yield current_taxon\n",
" remaining_taxons.extend(current_taxon.children)"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"pythonidae = Taxon(\"Pythonidae\", None)"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Pythonidae\n"
]
}
],
"source": [
"print(pythonidae.name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Task 4\n",
"\n",
"Use the Ensembl Taxonomy API to fetch a tree of taxonomic information. You should use the `child` array in the JSON returned by the API to determine the name (or ID) of child taxa."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"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",
"version": "3.6.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}