Python for Scientific Computing and Artificial Intelligence 1st Edition Stephen Lynch download pdf
Python for Scientific Computing and Artificial Intelligence 1st Edition Stephen Lynch download pdf
com
https://ebookmeta.com/product/python-for-scientific-
computing-and-artificial-intelligence-1st-edition-stephen-
lynch/
OR CLICK BUTTON
DOWNLOAD NOW
This book was developed from a series of national and international workshops that the author
has been delivering for over twenty years. The book is beginner friendly and has a strong practi-
cal emphasis on programming and computational modeling.
Features:
In 2022, Stephen Lynch was named a National Teaching Fellow, which celebrates and recognises
individuals who have made an outstanding impact on student outcomes and teaching in higher
education. He won the award for his work in programming in the STEM subjects, research
feeding into teaching, and widening participation (using experiential and object-based learn-
ing). Although educated as a pure mathematician, Stephen’s many interests now include applied
mathematics, cell biology, electrical engineering, computing, neural networks, nonlinear optics
and binary oscillator computing, which he co-invented with a colleague. He has authored 2 in-
ternational patents for inventions, 8 books, 4 book chapters, over 40 journal articles, and a few
conference proceedings. Stephen is a Fellow of the Institute of Mathematics and Its Applica-
tions (FIMA) and a Senior Fellow of the Higher Education Academy (SFHEA). He is currently
a Reader with MMU and was an Associate Lecturer with the Open University from 2008-2012.
In 2010, Stephen volunteered as a STEM Ambassador, in 2012, he was awarded MMU Public
Engagement Champion status, and in 2014 he became a Speaker for Schools. He runs national
workshops on “Python for A-Level Mathematics and Beyond,” and international workshops on
“Python for Scientific Computing and TensorFlow for Artificial Intelligence.” He has run work-
shops in China, Malaysia, Singapore, and the USA.
Chapman & Hall/CRC
The Python Series
About the Series
Python has been ranked as the most popular programming language, and it is widely used in
education and industry. This book series will offer a wide range of books on Python for students
and professionals. Titles in the series will help users learn the language at an introductory and
advanced level, and explore its many applications in data science, AI, and machine learning.
Series titles can also be supplemented with Jupyter notebooks.
Stephen Lynch
Manchester Metropolitan University, United Kingdom
First edition published 2023
by CRC Press
6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742
Reasonable efforts have been made to publish reliable data and information, but the author and publisher cannot
assume responsibility for the validity of all materials or the consequences of their use. The authors and publishers
have attempted to trace the copyright holders of all material reproduced in this publication and apologize to copyright
holders if permission to publish in this form has not been obtained. If any copyright material has not been acknowl-
edged please write and let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or
utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including pho-
tocopying, microfilming, and recording, or in any information storage or retrieval system, without written permission
from the publishers.
For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the
Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are
not available on CCC please contact mpkbookspermissions@tandf.co.uk
Trademark notice: Product or corporate names may be trademarks or registered trademarks and are used only for
identification and explanation without intent to infringe.
DOI: 10.1201/9781003285816
Typeset in LM Roman
by KnowledgeWorks Global Ltd.
Publisher’s note: This book has been prepared from camera-ready copy provided by the authors
To my family,
my brother Mark and my sister Jacqueline,
my wife Gaynor,
and our children, Sebastian and Thalia,
for their continuing love, inspiration and support.
Contents
Foreword xiii
Preface xv
1.1 INTRODUCTION 4
1.1.1 Tutorial One: Using Python as a Powerful Calculator (30
Minutes) 5
1.1.2 Tutorial Two: Lists (20 Minutes) 7
1.2 SIMPLE PROGRAMMING IN PYTHON 8
1.2.1 Tutorial Three: Defining Functions (30 Minutes) 9
1.2.2 Tutorial Four: For and While Loops (20 Minutes) 11
1.2.3 Tutorial Five: If, elif, else constructs (10 Minutes) 11
1.3 THE TURTLE MODULE AND FRACTALS 11
vii
viii Contents
Chapter 6 Biology 81
Chapter 7 Chemistry 95
Index 309
Foreword
I came to know about the author through his previous text: Dynamical Systems with
Applications using Python, Springer International Publishing (2018). I simply loved
this book as it helped me to enhance my knowledge in both Python and Dynamical
Systems. I was so pleased with this book that in collaboration with a senior colleague
in Dynamical Systems, we developed a set of two-semester courses with the same
title as the book. We also invited Stephen to offer for us a short course on Python for
Scientific Computing and TensorFlow for Artificial Intelligence (AI). We were very
pleased that he accepted our offer, as he has been in demand to offer these courses
all over the world. For Pitt, he first offered it online (due to Covid) in summer 2021,
and then in person on Pitt campus in summer 2022. Both of these courses were huge
successes with several hundreds of participants each time. These delegates came from
a wide variety of backgrounds: professors, scientists and engineers from a wide range
of disciplines in industry & government labs, and both graduate and undergraduate
students in a broad range of disciplines. The excellent textbook plus Stephen’s natural
teaching talents made the course very popular. We plan to offer it on a regular basis
as long as Stephen is up for it.
Based on these experiences, I was naturally very eager and excited to read
Stephen’s newest (present) text, and I am not surprised to see that this volume
is also a masterpiece! The topics and approach taken in this book are indeed like no
other! The first section provides an introduction to Python for complete novices and
goes on to show how it can be used for teaching High School mathematics. Readers
are shown how to access Python through the IDLE platform, Spyder and jupyter
notebooks through Anaconda, and cloud computing using Google Colab. The second
section covers a vast array of examples from the scientific fields of biology, chemistry,
data science, economics, engineering, fractals & multifractals, image processing, nu-
merical methods for ordinary and partial differential equations, physics and statistics.
Each chapter covers several examples from the field and there are exercises with even
more examples at the end of each chapter. The final section covers AI, with brain-
inspired computing and neurodynamics and neural networks following on nicely from
Section 2. The final chapters introduce TensorFlow and Keras, and recurrent and con-
volutional neural networks, respectively. There is further reading for those interested
in cyber security, ethics in AI, the internet of things, natural language processing and
reinforcement learning.
All Python and TensorFlow programs can be downloaded through GitHub and full
worked solutions for all of the exercises are available to view on the Web. Overall, the
book will appeal to a very wide range of readers, from high school, to undergraduate
and postgraduate students in science & engineering, to academics and researchers
xiii
xiv Foreword
in industry. Novices to programming and even experienced programmers will all get
something from this book.
Professor Lynch has recently been named a National Teaching Fellow in the
UK. I am not very familiar with UK’s system. But as I understand, this fellowship is
“...to recognize and celebrate individuals who have made an outstanding impact on
student outcomes and the teaching profession...” Based on his other books, and his
courses, I can easily see that Stephen is surely deserving of this recognition. He is an
excellent writer, with an exceptional knack for teaching.
I hope that the reader is as excited as I was to get started on this book.
I have found out within the last few days why so few men are to be
seen in my rounds. The settlements here scarcely deserve the name
of villages—they are too straggling for that; it is only now and then
that from one hut one can catch a distant glimpse of another. The
view is also obstructed by the fields of manioc, whose branches,
though very spreading, are not easily seen through on account of the
thickly-growing, succulent green foliage. This and the bazi pea are,
now that the maize and millet have been gathered in, the only crops
left standing in the fields. Thus it may happen that one has to trust
entirely to the trodden paths leading from one hut to another, to be
sure of missing none, or to the guidance of the sounds inseparable
from every human settlement. There is no lack of such noises at
Masasi, and in fact I follow them almost every day. Walking about
the country with Nils Knudsen, I hear what sounds like a jovial
company over their morning drink—voices becoming louder and
louder, and shouting all together regardless of parliamentary rules. A
sudden turn of the path brings us face to face with a drinking-party,
and a very merry one, indeed, to judge by the humour of the guests
and the number and dimensions of the pombe pots which have been
wholly or partially emptied. The silence which follows our
appearance is like that produced by a stone thrown into a pool where
frogs are croaking. Only when we ask, “Pombe nzuri?” (“Is the beer
good?”) a chorus of hoarse throats shouts back the answer—“Nzuri
kabisa, bwana!” (“Very good indeed, sir!”)
As to this pombe—well, we Germans fail to appreciate our
privileges till we have ungratefully turned our backs on our own
country. At Mtua, our second camp out from Lindi, a huge earthen
jar of the East African brew was brought as a respectful offering to us
three Europeans. At that time I failed to appreciate the dirty-looking
drab liquid; not so our men, who finished up the six gallons or so in a
twinkling. In Masasi, again, the wife of the Nyasa chief Masekera
Matola—an extremely nice, middle-aged woman—insisted on
sending Knudsen and me a similar gigantic jar soon after our arrival.
We felt that it was out of the question to refuse or throw away the
gift, and so prepared for the ordeal with grim determination. First I
dipped one of my two tumblers into the turbid mass, and brought it
up filled with a liquid in colour not unlike our Lichtenhain beer, but
of a very different consistency. A compact mass of meal filled the
glass almost to the top, leaving about a finger’s breadth of real, clear
“Lichtenhainer.” “This will never do!” I growled, and shouted to
Kibwana for a clean handkerchief. He produced one, after a
seemingly endless search, but my attempts to use it as a filter were
fruitless—not a drop would run through. “No use, the stuff is too
closely woven. Lete sanda, Kibwana” (“Bring a piece of the shroud!”)
This order sounds startling enough, but does not denote any
exceptional callousness on my part. Sanda is the Swahili name for
the cheap, unbleached and highly-dressed calico (also called bafta)
which, as a matter of fact, is generally used by the natives to wrap a
corpse for burial. The material is consequently much in demand, and
travellers into the interior will do well to carry a bale of it with them.
When the dressing is washed out, it is little better than a network of
threads, and might fairly be expected to serve the purpose of a filter.
I found, however, that I could not strain the pombe through it—a
few scanty drops ran down and that was all. After trying my tea and
coffee-strainers, equally in vain, I gave up in despair, and drank the
stuff as it stood. I found that it had a slight taste of flour, but was
otherwise not by any means bad, and indeed quite reminiscent of my
student days at Jena—in fact, I think I could get used to it in time.
The men of Masasi seem to have got only too well used to it. I am far
from grudging the worthy elders their social glass after the hard work
of the harvest, but it is very hard that my studies should suffer from
this perpetual conviviality. It is impossible to drum up any
considerable number of men to be cross-examined on their tribal
affinities, usages and customs. Moreover, the few who can reconcile
it with their engagements and inclinations to separate themselves for
a time from their itinerant drinking-bouts are not disposed to be very
particular about the truth. Even when, the other day, I sent for a
band of these jolly topers to show me their methods of
basketmaking, the result was very unsatisfactory—they did some
plaiting in my presence, but they were quite incapable of giving in
detail the native names of their materials and implements—the
morning drink had been too copious.
It is well known that it is the custom of most, if not all, African
tribes to make a part of their supply of cereals into beer after an
abundant harvest, and consume it wholesale in this form. This, more
than anything else, has probably given rise to the opinion that the
native always wastes his substance in time of plenty, and is nearly
starved afterwards in consequence. It is true that our black friends
cannot be pronounced free from a certain degree of “divine
carelessness”—a touch, to call it no more, of Micawberism—but it
would not be fair to condemn them on the strength of a single
indication. I have already laid stress on the difficulty which the
native cultivator has of storing his seed-corn through the winter. It
would be still more difficult to preserve the much greater quantities
of foodstuffs gathered in at the harvest in a condition fit for use
through some eight or nine months. That he tries to do so is seen by
the numerous granaries surrounding every homestead of any
importance, but that he does not invariably succeed, and therefore
prefers to dispose of that part of his crops which would otherwise be
wasted in a manner combining the useful and the agreeable, is
proved by the morning and evening beer-drinks already referred to,
which, with all their loud merriment, are harmless enough. They
differ, by the bye, from the drinking in European public-houses, in
that they are held at each man’s house in turn, so that every one is
host on one occasion and guest on another—a highly satisfactory
arrangement on the whole.
My difficulties are due to other causes besides the chronically
bemused state of the men. In the first place, there are the troubles
connected with photography. In Europe the amateur is only too
thankful for bright sunshine, and even should the light be a little
more powerful than necessary, there is plenty of shade to be had
from trees and houses. In Africa we have nothing of the sort—the
trees are neither high nor shady, the bushes are not green, and the
houses are never more than twelve feet high at the ridge-pole. To this
is added the sun’s position in the sky at a height which affects one
with a sense of uncanniness, from nine in the morning till after three
in the afternoon, and an intensity of light which is best appreciated
by trying to match the skins of the natives against the colours in Von
Luschan’s scale. No medium between glittering light and deep black
shadow—how is one, under such circumstances, to produce artistic
plates full of atmosphere and feeling?
For a dark-room I have been trying to use the Masasi boma. This is
the only stone building in the whole district and has been
constructed for storing food so as to prevent the recurrence of famine
among the natives, and, still more, to make the garrison independent
of outside supplies in the event of another rising. It has only one
story, but the walls are solidly built, with mere loopholes for
windows; and the flat roof of beaten clay is very strong. In this
marvel of architecture are already stacked uncounted bags
containing millet from the new crop, and mountains of raw cotton. I
have made use of both these products, stopping all crevices with the
cotton, and taking the bags of grain to sit on, and also as a support
for my table, hitherto the essential part of a cotton-press which
stands forsaken in the compound, mourning over the shipwreck it
has made of its existence. Finally, I have closed the door with a
combination of thick straw mats made by my carriers, and some
blankets from my bed. In this way, I can develop at a pinch even in
the daytime, but, after working a short time in this apartment, the
atmosphere becomes so stifling that I am glad to escape from it to
another form of activity.
On one of my first strolls here, I came upon
a neat structure which was explained to me as
“tego ya ngunda”—a trap for pigeons. This is
a system of sticks and thin strings, one of
which is fastened to a strong branch bent over
into a half-circle. I have been, from my youth
up, interested in all mechanical contrivances,
and am still more so in a case like this, where
we have an opportunity of gaining an insight
into the earlier evolutional stages of the
RAT TRAP human intellect. I therefore, on my return to
camp, called together all my men and as many
local natives as possible, and addressed the assembly to the effect
that the mzungu was exceedingly anxious to possess all kinds of
traps for all kinds of animals. Then followed the promise of good
prices for good and authentic specimens, and the oration wound up
with “Nendeni na tengenezeni sasa!” (“Now go away and make up
your contraptions!”).
How they hurried off that day, and how eagerly all my men have
been at work ever since! I had hitherto believed all my carriers to be
Wanyamwezi—now I find, through the commentaries which each of
them has to supply with his work, that my thirty men represent a
number of different tribes. Most of them, to be sure, are
Wanyamwezi, but along with them there are some Wasukuma and
Manyema, and even a genuine Mngoni from Runsewe, a
representative of that gallant Zulu tribe who, some decades ago,
penetrated from distant South Africa to the present German
territory, and pushed forward one of its groups—these very Runsewe
Wangoni—as far as the south-western corner of the Victoria Nyanza.
As for the askari, though numbering only thirteen, they belong to no
fewer than twelve different tribes, from those of far Darfur in the
Egyptian Sudan to the Yao in Portuguese East Africa. All these
“faithfuls” have been racking their brains to recall and practise once
more in wood and field the arts of their boyhood, and now they come
and set up, in the open, sunny space beside my palatial abode, the
results of their unwonted intellectual exertions.
The typical cultivator is not credited in literature with much skill
as a hunter and trapper; his modicum of intellect is supposed to be
entirely absorbed by the care of his fields, and none but tribes of the
stamp of the Bushmen, the Pygmies and the Australian aborigines
are assumed by our theoretic wisdom to be capable of dexterously
killing game in forest or steppe, or taking it by skilful stratagem in a
cunningly devised trap. And yet how wide of the mark is this opinion
of the schools! Among the tribes of the district I am studying, the
Makua are counted as good hunters, while at the same time they are
like the rest, in the main, typical hoe-cultivators—i.e., people who,
year after year, keep on tilling, with the primitive hoe, the ground
painfully brought under cultivation. In spite of their agricultural
habits their traps are constructed with wonderful ingenuity. The
form and action of these traps is sufficiently evident from the
accompanying sketches; but in case any reader should be entirely
without the faculty of “technical sight,” I may add for his benefit that
all these murderous implements depend on the same principle.
Those intended for quadrupeds are so arranged that the animal in
walking or running forward strikes against a fine net with his muzzle,
or a thin cord with his foot. The net or the string is thereby pressed
forward, the upper edge of the former glides downwards, but the end
of the string moves a little to one side. In either case this movement
sets free the end of a lever—a small stick which has hitherto, in a way
sufficiently clear from the sketch—kept the trap set. It slips
instantaneously round its support, and in so doing releases the
tension of the tree or bent stick acting as a spring, which in its
upward recoil draws a skilfully fixed noose tight round the neck of
the animal, which is then strangled to death. Traps of similar
construction, but still more cruel, are set for rats and the like, and,
unfortunately, equal cunning and skill are applied to the pursuit of
birds. Perhaps I shall find another opportunity of discussing this side
of native life; it certainly deserves attention, for there is scarcely any
department where the faculty of invention to be found in even the
primitive mind is so clearly shown as in this aspect of the struggle for
existence.
It is not very easy to locate my present abode on the map. Masasi and
its exact latitude and longitude have been known to me for years, but
of this strangely named place,[17] where I drove in my tent-pegs a few
days ago, I never even heard before I had entered the area of the
inland tribes.
One trait is common to all Oriental towns, their beauty at a
distance and the disillusionment in store for those who set foot
within their walls. Knudsen has done nothing but rave about
Chingulungulu ever since we reached Masasi. He declared that its
baraza was the highest achievement of East African architecture,
that it had a plentiful supply of delicious water, abundance of all
kinds of meat, and unequalled fruit and vegetables. He extolled its
population, exclusively composed, according to him, of high-bred
gentlemen and good-looking women, and its well-built, spacious
houses. Finally, its situation, he said, made it a convenient centre for
excursions in all directions over the plain. I have been here too short
a time to bring all the details of this highly coloured picture to the
test of actual fact, but this much I have already ascertained, that
neither place nor people are quite so paradisaical as the enthusiastic
Nils would have me believe.
YAO HOMESTEAD AT CHINGULUNGULU
His name, Kofia tule, was at first a puzzle to me. I knew that kofia
means a cap, but, curiously enough it never occurred to me to look
up tule (which, moreover, I assumed to be a Nyamwezi word) in the
dictionary. That it was supposed to involve a joke of some sort, I
gathered from the general laughter, whenever I asked its meaning. At
last we arrived at the fact that kofia tule means a small, flat cap—in
itself a ridiculous name for a man, but doubly so applied to this black
super-man with the incredibly vacant face.
Kofia tule, then, comes slowly forward, followed by six more
Wanyamwezi, and some local men whom I have engaged as extra
carriers. With him as their mnyampara they are to take my
collections down to the Coast, and get them stored till my return in
the cellars of the District Commissioner’s office at Lindi. The final
instructions are delivered, and then comes the order, “You here, go
to the left,—we are going to the right. March!” Our company takes
some time to get into proper marching order, but at last everything
goes smoothly. A glance northward over the plain assures us that
Kofia tule and his followers have got up the correct safari speed; and
we plunge into the uninhabited virgin pori.
There is something very monotonous and fatiguing about the
march through these open woods. It is already getting on for noon,
and I am half-asleep on my mule, when I catch sight of two black
figures, gun in hand, peeping cautiously round a clump of bushes in
front. Can they be Wangoni?
For some days past we have heard flying rumours that Shabruma,
the notorious leader of the Wangoni in the late rebellion, and the last
of our opponents remaining unsubdued, is planning an attack on
Nakaam, and therefore threatening this very neighbourhood. Just as
I look round for my gun-bearer, a dozen throats raise the joyful shout
of “Mail-carrier!” This is my first experience of the working of the
German Imperial Post in East Africa; I learnt in due course that,
though by no means remunerative to the department, it is as nearly
perfect as any human institution can be. It sounds like an
exaggeration, but it is absolutely true, to say that all mail matter,
even should it be only a single picture post-card, is delivered to the
addressee without delay, wherever he may be within the postal area.
The native runners, of course, have a very different sort of duty to
perform from the few miles daily required of our home functionaries.
With letters and papers packed in a water-tight envelope of oiled
paper and American cloth, and gun on shoulder, the messenger trots
along, full of the importance of his errand, and covers enormous
distances, sometimes, it is said, double the day’s march of an
ordinary caravan. If the road lies through a district rendered unsafe
by lions, leopards, or human enemies, two men are always sent
together. The black figures rapidly approach us, ground arms with
soldierly precision and report in proper form:—Letters from Lindi
for the Bwana mkubwa and the Bwana mdogo—the great and the
little master. As long as Mr. Ewerbeck was with us, it was not easy for
the natives to establish the correct precedence between us. Since they
ranked me as the new captain, they could not possibly call me
Bwana mdogo. Now, however, there is not the slightest difficulty,—
there are only two Europeans, and I being, not only the elder, but
also the leader of the expedition, there is nothing to complicate the
usual gradation of ranks.