Python for Scientists 2nd Edition John M. Stewart pdf download
Python for Scientists 2nd Edition John M. Stewart pdf download
Stewart download
https://textbookfull.com/product/python-for-scientists-2nd-
edition-john-m-stewart/
https://textbookfull.com/product/python-for-data-science-2nd-
edition-john-paul-mueller/
https://textbookfull.com/product/beginning-programming-with-
python-for-dummies-2nd-edition-john-paul-mueller/
https://textbookfull.com/product/programming-with-python-for-
social-scientists-1st-edition-phillip-brooker/
https://textbookfull.com/product/python-programming-an-
introduction-to-computer-science-john-m-zelle/
The Boundary Element Method for Engineers and
Scientists Theory and Applications 2nd Edition John T.
Katsikadelis
https://textbookfull.com/product/the-boundary-element-method-for-
engineers-and-scientists-theory-and-applications-2nd-edition-
john-t-katsikadelis/
https://textbookfull.com/product/python-programming-an-
introduction-to-computer-science-3rd-edition-john-m-zelle/
https://textbookfull.com/product/prototyping-python-dashboards-
for-scientists-and-engineers-build-and-deploy-a-complete-
dashboard-with-python-1st-edition-houlahan/
https://textbookfull.com/product/mathematics-pocket-book-for-
engineers-and-scientists-5th-edition-john-bird/
https://textbookfull.com/product/mathematics-pocket-book-for-
engineers-and-scientists-5th-edition-john-bird-2/
Python for Scientists
Second Edition
Scientific Python is a significant public domain alternative to expensive proprietary soft-
ware packages. This book teaches from scratch everything the working scientist needs
to know using copious, downloadable, useful and adaptable code snippets. Readers will
discover how easy it is to implement and test non-trivial mathematical algorithms and
will be guided through the many freely available add-on modules. A range of exam-
ples, relevant to many different fields, illustrate the language’s capabilities. The author
also shows how to use pre-existing legacy code (usually in Fortran77) within the Python
environment, thus avoiding the need to master the original code.
In this new edition, several chapters have been rewritten to reflect the IPython note-
book style. With an extended index, an entirely new chapter discussing SymPy and a
substantial increase in the number of code snippets, researchers and research students
will be able to quickly acquire all the skills needed for using Python effectively.
Python for Scientists
Second Edition
J O H N M . S T E WA RT
Department of Applied Mathematics & Theoretical Physics
University of Cambridge
University Printing House, Cambridge CB2 8BS, United Kingdom
One Liberty Plaza, 20th Floor, New York, NY 10006, USA
477 Williamstown Road, Port Melbourne, VIC 3207, Australia
4843/24, 2nd Floor, Ansari Road, Daryaganj, Delhi – 110002, India
79 Anson Road, #06–04/06, Singapore 079906
www.cambridge.org
Information on this title: www.cambridge.org/9781316641231
DOI: 10.1017/9781108120241
c John M. Stewart 2014, 2017
This publication is in copyright. Subject to statutory exception
and to the provisions of relevant collective licensing agreements,
no reproduction of any part may take place without the written
permission of Cambridge University Press.
First published 2014
Second edition 2017
Printed in the United Kingdom by TJ International Ltd. Padstow Cornwall
A catalogue record for this publication is available from the British Library.
Library of Congress Cataloging-in-Publication Data
Names: Stewart, John, 1943 July 1–
Title: Python for scientists / John M. Stewart, Department of Applied, Mathematics & Theoretical
Physics, University of Cambridge.
Description: Second edition. | Cambridge, United Kingdom ; New York, NY, USA : Cambridge
University Press, [2017] | Includes bibliographical references and index.
Identifiers: LCCN 2016049298 | ISBN 9781316641231 (paperback)
Subjects: LCSH: Science–Data processing. | Python (Computer program language)
Classification: LCC Q183.9 .S865 2017 | DDC 005.13/3–dc23
LC record available at https://lccn.loc.gov/2016049298
ISBN 978-1-316-64123-1 Paperback
Additional resources for this publication at www.cambridge.org/9781316641231
Cambridge University Press has no responsibility for the persistence or accuracy
of URLs for external or third-party Internet Web sites referred to in this publication
and does not guarantee that any content on such Web sites is, or will remain,
accurate or appropriate.
Contents
1 Introduction 1
1.1 Scientific Software 1
1.2 The Plan of This Book 4
1.3 Can Python Compete with Compiled Languages? 8
1.4 Limitations of This Book 9
1.5 Installing Python and Add-ons 9
3.5.6 Strings 33
3.5.7 Dictionaries 33
3.6 Python if Statements 34
3.7 Loop Constructs 35
3.7.1 The Python for loop 35
3.7.2 The Python continue statement 37
3.7.3 The Python break statement 37
3.7.4 List comprehensions 38
3.7.5 Python while loops 39
3.8 Functions 39
3.8.1 Syntax and scope 40
3.8.2 Positional arguments 43
3.8.3 Keyword arguments 43
3.8.4 Variable number of positional arguments 43
3.8.5 Variable number of keyword arguments 44
3.8.6 Python input/output functions 44
3.8.7 The Python print function 45
3.8.8 Anonymous functions 47
3.9 Introduction to Python Classes 47
3.10 The Structure of Python 50
3.11 Prime Numbers: A Worked Example 51
4 NumPy 55
4.1 One-Dimensional Arrays 57
4.1.1 Ab initio constructors 57
4.1.2 Look-alike constructors 58
4.1.3 Arithmetical operations on vectors 59
4.1.4 Ufuncs 60
4.1.5 Logical operations on vectors 62
4.2 Two-Dimensional Arrays 65
4.2.1 Broadcasting 65
4.2.2 Ab initio constructors 66
4.2.3 Look-alike constructors 68
4.2.4 Operations on arrays and ufuncs 69
4.3 Higher-Dimensional Arrays 69
4.4 Domestic Input and Output 69
4.4.1 Discursive output and input 70
4.4.2 NumPy text output and input 71
4.4.3 NumPy binary output and input 72
4.5 Foreign Input and Output 73
4.5.1 Small amounts of data 73
4.5.2 Large amounts of data 73
4.6 Miscellaneous Ufuncs 74
4.6.1 Maxima and minima 74
Contents vii
5 Two-Dimensional Graphics 82
5.1 Introduction 82
5.2 Getting Started: Simple Figures 83
5.2.1 Front-ends 83
5.2.2 Back-ends 83
5.2.3 A simple figure 84
5.2.4 Interactive controls 86
5.3 Object-Oriented Matplotlib 87
5.4 Cartesian Plots 88
5.4.1 The Matplotlib plot function 88
5.4.2 Curve styles 89
5.4.3 Marker styles 90
5.4.4 Axes, grid, labels and title 90
5.4.5 A not-so-simple example: partial sums of Fourier series 91
5.5 Polar Plots 93
5.6 Error Bars 94
5.7 Text and Annotations 95
5.8 Displaying Mathematical Formulae 96
5.8.1 Non-LATEX users 96
5.8.2 LATEX users 97
5.8.3 Alternatives for LATEX users 98
5.9 Contour Plots 98
5.10 Compound Figures 101
5.10.1 Multiple figures 101
5.10.2 Multiple plots 102
5.11 Mandelbrot Sets: A Worked Example 104
References 250
Index 253
Preface to the Second Edition
The motivation for writing this book, and the acknowledgements of the many who have
assisted in its production, are included in the topics of the Preface to the first edition,
which is reprinted after this one. Here I also need to adjoin thanks to the many readers
who provided constructive criticisms, most of which have been incorporated in this
revision. The purpose here is to explain why a second edition is needed. Superficially it
might appear that very little has changed, apart from a new Chapter 7 which discusses
SymPy, Python’s own computer algebra system.
There is, however, a fundamental change, which permeates most of the latest version
of this book. When the first edition was prepared, the reliable way to use the enhanced
interpreter IPython was via the traditional “terminal mode”. Preparations were under
way for an enhanced “notebook mode”, which looked then rather like the Mathemat-
ica notebook concept, except that it appeared within one’s default web browser.1 That
project has now morphed into the Jupyter notebook. The notebook allows one to con-
struct and distribute documents containing computer code (over forty languages are
supported), equations, explanatory text, figures and visualizations. Since this is also
perhaps the easiest software application for a beginner to develop Python experience,
much of the book has been rewritten for the notebook user. In particular there is now
a lightning course on how to use the notebook in Appendix A, and Chapter 2 has been
extensively rewritten to demonstrate its properties. All of the material in the book now
reflects, where appropriate, its use. For example, it allows SymPy to produce algebraic
expressions whose format is unsurpassed by other computer algebra systems.
This change also affects the areas of interactive graphics and visual animations. Their
demands are such that the standard Python two-dimensional graphics package Mat-
plotlib is having difficulty in producing platform-independent results. Indeed, because
of “improved” software upgrades, the code suggested for immediate on-screen anima-
tions in the first edition no longer works. However, the notebook concept has a subtle
solution to resolve this impasse. Recall that the notebook window is your browser win-
dow, which uses modern HTML graphics. The consequent benefits are introduced in
Chapter 6.
As a final enhancement, all but the most trivial code snippets listed in this book are
now available in electronic form, as a notebook of course, but the website includes
HTML and PDF versions, see Section 1.2. The explanatory text surrounding the text is
not included. For that you have to read the book, in hard copy or ebook format!
I have used computers as an aid to scientific research for over 40 years. During that
time, hardware has become cheap, fast and powerful. However, software relevant to the
working scientist has become progressively more complicated. My favourite textbooks
on Fortran90 and C++ run to 1200 and 1600 pages respectively. And then we need doc-
umentation on mathematics libraries and graphics packages. A newcomer going down
this route is going to have to invest significant amounts of time and energy in order to
write useful programmes. This has led to the emergence of “scientific packages” such
as Matlab® or Mathematica® which avoid the complications of compiled languages,
separate mathematics libraries and graphics packages. I have used them and found them
very convenient for executing the tasks envisaged by their developers. However, I also
found them very difficult to extend beyond these boundaries, and so I looked for alter-
native approaches.
Some years ago, a computer science colleague suggested that I should take a look at
Python. At that time, it was clear that Python had great potential but a very flaky imple-
mentation. It was, however, free and open-source, and was attracting what has turned
out to be a very effective army of developers. More recently, their efforts have coordi-
nated to produce a formidable package consisting of a small core language surrounded
by a wealth of add-on libraries or modules. A select group of these can and do replicate
the facilities of the conventional scientific packages. More importantly an informed, in-
telligent user of Python and its modules can carry out major projects usually entrusted
to dedicated programmers using Fortran, C etc. There is a marginal loss of execution
speed, but this is more than compensated for by the vastly telescoped development time.
The purpose of this book is to explain to working scientists the utility of this relatively
unknown resource.
Most scientists will have some computer familiarity and programming awareness,
although not necessarily with Python, and I shall take advantage of this. Therefore,
unlike many books which set out to “teach” a language, this one is not just a brisk trot
through the reference manuals. Python has many powerful but unfamiliar facets, and
these need more explanation than the familiar ones. In particular, if you encounter in
this text a reference to the “beginner” or the “unwary”, it signifies a point which is not
made clear in the documentation, and has caught out this author at least once.
The first seven chapters, plus Appendix A, cover almost everything the working sci-
entist needs to know in order to get started in using Python effectively. My editor and
some referees suggested that I should devote the second half of the book to problems in
xiv Preface to the First Edition
a particular field. This would have led to a series of books, “Python for Biochemists”,
“Python for Crystallographers”, . . . , all with a common first half. Instead I have cho-
sen to cover just three topics, which, however, should be far more widely applicable in
many different fields. Chapter 8 covers four radically different types of ordinary differ-
ential equations and shows how to use the various relevant black boxes, which are often
Python wrappers around tried and trusted Fortran codes. The next chapter while os-
tensibly about pseudospectral approaches to evolutionary partial differential equations,
actually covers a topic of great utility to many scientists, namely how to reuse legacy
code, usually written in Fortran77, within Python at Fortran-like speeds, without under-
standing Fortran. The final chapter about solving very large linear systems via multigrid
is also a case history in how to use object-oriented programming meaningfully in a sci-
entific context. If readers look carefully and critically at these later chapters, they should
gain the practical expertise to handle problems in their own field.
Acknowledgments are due to the many Python developers who have produced and
documented a very useful tool, and also to the very many who have published code
snippets on the web, a great aid to the tyro, such as this author. Many of my colleagues
have offered valuable advice. Des Higham generously consented to my borrowing his
ideas for the last quarter of Chapter 8. I am especially grateful to Oliver Rinne who read
carefully and critically an early draft. At Cambridge University Press, my Production
Editor, Jessica Murphy and my Copy Editor, Anne Rix have exhibited their customary
expertise. Last but not least I thank the Department of Applied Mathematics and Theo-
retical Physics, Cambridge for continuing to offer me office space after my retirement,
which has facilitated the production of this book.
Writing a serious book is not a trivial task and so I am rather more than deeply
grateful for the near-infinite patience of Mary, the “Python-widow”, which made this
book possible!
1 Introduction
The title of this book is “Python for Scientists”, but what does that mean? The dictio-
nary defines “Python” as either (a) a non-venomous snake from Asia or Saharan Africa
or (b) a computer scripting language, and it is the second option which is intended here.
(What exactly this second definition means will be explained later.) By “scientist”, I
mean anyone who uses quantitative models either to obtain conclusions by processing
pre-collected experimental data or to model potentially observable results from a more
abstract theory, and who asks “what if?”. What if I analyse the data in a different way?
What if I change the model? Thus the term also includes economists, engineers and
mathematicians among others, as well as the usual concept of scientists. Given the vol-
ume of potential data or the complexity (non-linearity) of many theoretical models, the
use of computers to answer these questions is fast becoming mandatory.
Advances in computer hardware mean that immense amounts of data or ever more
complex models can be processed at increasingly rapid speeds. These advances also
mean reduced costs so that today virtually every scientist has access to a “personal
computer”, either a desktop work station or a laptop, and the distinction between the
two is narrowing quickly. It might seem to be a given that suitable software will also be
available so that the “what if” questions can be answered readily. However, this turns
out not always to be the case. A quick pragmatic reason is that, while there is a huge
market for hardware improvements, scientists form a very small fraction of it and so
there is little financial incentive to improve scientific software. But for scientists, this
issue is important and we need to examine it in more detail.
Before we discuss what is available, it is important to note that all computer software
comes in one of two types: proprietary and open-source. The first is supplied by a com-
mercial firm. Such organizations have both to pay wages and taxes and to provide a re-
turn for their shareholders. Therefore, they have to charge real money for their products,
and, in order to protect their assets from their competitors, they do not tell the customer
how their software works. Thus, the end-users have little chance of being able to adapt
or optimize the product for their own use. Since wages and taxes are recurrent expendi-
tures, the company needs to issue frequent charged-for updates and improvements (the
Danegeld effect). Open-source software is available for free or at nominal cost (media,
2 Introduction
algebraic and analytic processes, and to integrate all of them with their numerical and
graphical properties. A disadvantage of all of these packages is the quirky syntax and
limited expressive ability of their command languages. Unlike the compiled languages,
it is often extremely difficult to program a process which was not envisaged by the
package authors.
The best of the proprietary packages are very easy to use with extensive on-line help
and coherent documentation, which has not yet been matched by all of the open-source
alternatives. However, a major downside of the commercial packages is the extremely
high prices charged for their licences. Most of them offer a cut down “student version”
at reduced price (but usable only while the student is in full-time education) so as to
encourage familiarity with the package. This largesse is paid for by other users.
Let us summarize the position. On the one hand, we have the traditional compiled
languages for numerics which are very general, very fast, very difficult to learn and do
not interact readily with graphical or algebraic processes. On the other, we have standard
scientific packages which are good at integrating numerics, algebra and graphics, but are
slow and limited in scope.
What properties should an ideal scientific package have? A short list might contain:
1. a mature programming language which is both easy to understand and which has
extensive expressive ability,
2. integration of algebraic, numerical and graphical functions,
3. the ability to generate numerical algorithms running with speeds within an order of
magnitude of the fastest of those generated by compiled languages,
4. a user interface with adequate on-line help, and decent documentation,
5. an extensive range of textbooks from which the curious reader can develop greater
understanding of the concepts,
6. open-source software, freely available,
7. implementation on all standard platforms, e.g., Linux, Mac OS X, Unix, Windows,
8. a concise package, and so implementable on even modest hardware.
The bad news is that no single “scientific package” quite satisfies all of these criteria.
Consider, e.g., the requirement of algebraic capability. There are two mature open-
source packages, wx-Maxima and Reduce, with significant algebraic capabilities worthy
of consideration, but Reduce fails requirement 4 and both fail criteria 3 and 5. They are,
however, extremely powerful tools in the hands of experienced users. Python, via the
add-on SymPy, see Chapter 7, almost achieves a high standard of algebraic capability.
SageMath fulfils all but the last of the criteria listed above. It is completely based on
Python and its add-ons, and also includes wx-Maxima. For further details see Chapter
7. Thus a rational strategy is to first master Python. If its, admirably few, weaknesses are
crucial for your work, then investigate SageMath. The vast majority of scientists will
find plenty of utility in Python.
In 1991, Guido van Rossum created Python as an open-source platform-independent
general purpose programming language. It is basically a very simple language sur-
rounded by an enormous library of add-on modules, including complete access to the
underlying operating system. This means that it can manage and manipulate programs
4 Introduction
built from other complete (even compiled) packages, i.e., it is a scripting language. This
versatility has ensured both its adoption by power users such as Google, and a real army
of developers. It means also that it can be a very powerful tool for the scientist. Of
course, there are other scripting languages, e.g., Java™ and Perl®, but none has the
versatility or user-base to meet criteria 3–5 above.
Ten years ago it would not have been possible to recommend Python for scientific
work. The size of the army of developers meant that there were several mutually incom-
patible add-on packages for numerical and scientific applications. Fortunately, reason
has prevailed and there is now a single numerical add-on package, NumPy, and a single
scientific one, SciPy, around which the developers have united. When the first edition
of this book was written SymPy, the Python approach to algebraic manipulation, was
still in a phase of rapid development, and so it was not included. While SymPy has yet
to achieve the capabilities of wx-Maxima and Reduce, it now handles many algebraic
tasks reliably
The purpose of this intentionally short book is to show how easy it is for the working
scientist to implement and test non-trivial mathematical algorithms using Python. We
have quite deliberately preferred brevity and simplicity to encyclopaedic coverage in
order to get the inquisitive reader up and running as soon as possible. We aim to leave
the reader with a well-founded framework to handle many basic, and not so basic, tasks.
Obviously, most readers will need to dig further into techniques for their particular
research needs. But after reading this book, they should have a sound basis for this.
This chapter and Appendix A discuss how to set up a scientific Python environment.
While the original Python interpreter was pretty basic, its replacement IPython is so
easy to use, powerful and versatile that Chapter 2 is devoted to it, adopting a hands-on
approach.
We now describe the subsequent chapters. As each new feature is described, we try
to illustrate it first by essentially trivial examples and, where appropriate, by more ex-
tended problems. This author cannot know the mathematical sophistication of potential
readers, but in later chapters we shall presume some familiarity with basic calculus,
e.g., the Taylor series in one dimension. However, for these extended problems we shall
sketch the background needed to understand them, and suitable references for further
reading will be given.
Chapter 3 gives a brief but reasonably comprehensive survey of those aspects of the
core Python language likely to be of most interest to scientists. Python is an object-
oriented language, which lends itself naturally to object-oriented programming (OOP),
which may well be unfamiliar to most scientists. We shall adopt an extremely light
touch to this topic. We should perhaps point out that the container objects introduced
in Section 3.5 do not all have precise analogues in, say, C or Fortran. Again the brief
introduction to Python classes in Section 3.9 may be unfamiliar to users of those two
families of languages. The chapter concludes with two implementations of the sieve
1.2 The Plan of This Book 5
These first chapters cover the basic tools that Python provides to enhance the scien-
tist’s computer experience. How should we proceed further?
A notable omission is that apart, from a brief discussion in Section 4.5, the vast
subject of data analysis will not be covered. There are three main reasons for this.
(a) Recently an add-on module called Pandas has appeared. This uses NumPy and Mat-
plotlib to tackle precisely this issue. It comes with comprehensive documentation,
which is described in Section 4.5.
(b) One of the authors of Pandas has written a book, McKinney (2012), which reviews
IPython, NumPy and Matplotlib and goes on to treat Pandas applications in great
detail.
(c) I do not work in this area, and so would simply have to paraphrase the sources
above.
Instead, I have chosen to concentrate on the modelling activities of scientists. One
approach would be to target problems in bioinformatics or cosmology or crystallogra-
phy or engineering or epidemiology or financial mathematics or . . . etc. Indeed, a whole
series of books with a common first half could be produced called “Python for Bioin-
formatics” etc. A less profligate and potentially more useful approach would be to write
a second half applicable to all of these fields, and many more. I am relying here on the
unity of mathematics. Problems in one field when reduced to a core dimensionless form
often look like a similarly reduced problem from another field.
This property can be illustrated by the following example. In population dynamics,
we might study a single species whose population N(T ) depends on time T . Given a
plentiful food supply, we might expect exponential growth, dN/dT = kN(T ), where the
growth constant k has dimension 1/time. However, there are usually constraints limiting
such growth. A simple model to include these is the “logistic equation”
dN
(T ) = kN(T ) (N0 − N(T )) (1.1)
dT
which allows for a stable constant population N(T ) = N0 . The biological background to
this equation is discussed in many textbooks, e.g., Murray (2002).
In (homogeneous spherically symmetric) cosmology, the density parameter Ω de-
pends on the scale factor a via
dΩ (1 + 3w)
= Ω(1 − Ω), (1.2)
da a
where w is usually taken to be a constant.
Now mathematical biology and cosmology do not have a great deal in common, but
it is easy to see that (1.1) and (1.2) represent the same equation. Suppose we scale the
independent variable T in (1.1) by t = kN0 T , which renders the new time coordinate
t dimensionless. Similarly, we introduce the dimensionless variable x = N/N0 so that
(1.1) becomes the logistic equation
dx
= x(1 − x). (1.3)
dt
In a general relativistic theory, there is no reason to prefer any one time coordinate to
1.2 The Plan of This Book 7
any other. Thus we may choose a new time coordinate t via a = et/(1+3w) , and then,
on setting x = Ω, we see that (1.2) also reduces to (1.3). Thus the same equations
can arise in a number of different fields.3 In Chapters 8–10, we have, for brevity and
simplicity, used minimal equations such as (1.3). If the minimal form for your problem
looks something like the one being treated in a code snippet, you can of course hack the
snippet to handle the original long form for your problem.
Chapter 8 looks at four types of problems involving ordinary differential equations.
We start with a very brief introduction to techniques for solving initial value problems
and then look at a number of examples, including two classic non-linear problems, the
van der Pol oscillator and the Lorenz equations. Next we survey two-point boundary
value problems and examine both a linear Sturm–Liouville eigenvalue problem and an
exercise in continuation for the non-linear Bratu problem. Problems involving delay dif-
ferential equations arise frequently in control theory and in mathematical biology, e.g.,
the logistic and Mackey–Glass equations, and a discussion of their numerical solution
is given in the next section. Finally in this chapter we look briefly at stochastic calcu-
lus and stochastic ordinary differential equations. In particular, we consider a simple
example closely linked to the Black–Scholes equation of financial mathematics.
There are two other major Python topics relevant to scientists that I would like to
introduce here. The first is the incorporation of code written in other languages. There
are two aspects of this: (a) the reuse of pre-existing legacy code, usually written in
Fortran, (b) if one’s code is being slowed down seriously by a few Python functions, as
revealed by the profiler, how do we recode the offending functions in Fortran or C? The
second topic is how can a scientific user make worthwhile use of the object-oriented
programming (OOP) features of Python?
Chapter 9 addresses the first topic via an extended example. We look first at how
pseudospectral methods can be used to attack a large number of evolution problems
governed by partial differential equations, either initial value or initial-boundary value
problems. For the sake of brevity, we look only at problems with one time and one
spatial dimension. Here, as we explain, problems with periodic spatial dependence can
be handled very efficiently using Fourier methods, but for problems which are more
general, the use of Chebyshev transforms is desirable. However, in this case there is
no satisfactory Python black box available. It turns out that the necessary tools have
already been written in legacy Fortran77 code. These are listed in Appendix B, and we
show how, with an absolutely minimal knowledge of Fortran77, we can construct ex-
tremely fast Python functions to accomplish the required tasks. Our approach relies on
the NumPy f2py tool which is included in all of the recommended Python distributions.
If you are interested in possibly reusing pre-existing legacy code, it is worthwhile study-
ing this chapter even if the specific example treated there is not the task that you have
in mind. See also Section 1.3 for other uses for f2py.
One of the most useful features of object-oriented programming (OOP) from the
point of view of the scientist is the concept of classes. Classes exist in C++ (but not
3 This example was chosen as a pedagogic example. If the initial value x(0) = x0 is specified, then the exact
solution is x(t) = x0 /[x0 + (1 − x0 )e−t ]. In the current context, x0 0. If x0 1, then all solutions tend
monotonically towards the constant solution x = 1 as t increases. See also Section 8.5.3.
8 Introduction
C) and Fortran90 and later (but not Fortran77). However, both implementations are
complicated and so are usually shunned by novice programmers. In contrast, Python’s
implementation is much simpler and more user-friendly, at the cost of omitting some of
the more arcane features of other language implementations. We give a very brief intro-
duction to the syntax in Section 3.9. However, in Chapter 10 we present a much more
realistic example: the use of multigrid to solve elliptic partial differential equations in
an arbitrary number of dimensions, although for brevity the example code is for two di-
mensions. Multigrid is by now a classical problem which is best defined recursively, and
we devote a few pages to describing it, at least in outline. The pre-existing legacy code
is quite complicated because the authors needed to simulate recursion in languages,
e.g., Fortran77, which do not support recursion. Of course, we could implement this
code using the f2py tool outlined in Chapter 9. Instead, we have chosen to use Python
classes and recursion to construct a simple clear multigrid code. As a concrete example,
we use the sample problem from the corresponding chapter in Press et al. (2007) so
that the inquisitive reader can compare the non-recursive and OOP approaches. If you
have no particular interest in multigrid, but do have problems involving linked math-
ematical structures, and such problems arise often in, e.g., bioinformatics, chemistry,
epidemiology and solid-state physics among others, then you should certainly peruse
this final chapter to see how, if you state reasonably mathematically precisely what your
problems are, then it is easy to construct Python code to solve them.
The most common criticism of Python and the scientific software packages is that they
are far too slow, in comparison with compiled code, when handling complicated realistic
problems. The speed-hungry reader might like to look at a recent study4 of a straight-
forward “number-crunching” problem treated by various methods. Although the figures
given in the final section refer to one particular problem treated on a single processor,
they do give a “ball park” impression of performance. As a benchmark, they use the
speed of a fully compiled C++ program which solves the problem. A Python solution
using the technique of Chapter 3, i.e., core Python, is about 700 times slower. Once
you use the floating-point module NumPy and the techniques described in Chapter 4
the code is only about ten times slower, and the Matlab performance is estimated to be
similar. However, as the study indicates, there are a number of ways to speed up Python
to about 80% of the C++ performance. Some of these are very rewarding exercises in
computer science.
One in particular, though, is extremely useful for scientists: the f2py tool. This is
discussed in detail in Chapter 9, where we show how we can reuse legacy Fortran code.
It can also be used to access standard Fortran libraries, e.g., the NAG libraries.5 Yet
another use is to speed up NumPy code and so improve performance! To see how this
works, suppose we have developed a program such as those outlined in the later sections
4 See http://wiki.scipy.org/PerformancePython.
5 See, e.g., http://www.nag.co.uk/doc/TechRep/pdf/TR1_08.pdf.
1.4 Limitations of This Book 9
of the book, which uses a large number of functions, each of which carries out a simple
task. The program works correctly, but is unacceptably slow. Note that getting detailed
timing data for Python code is straightforward. Python includes a “profiler” which can
be run on the working program. This outputs a detailed list of the functions ordered by
the time spent executing them. It is very easy to use, and this is described in Section 2.5.
Usually, there are one or two functions which take a very long time to execute simple
algorithms.
This is where f2py comes into its own. Because the functions are simple, even begin-
ners can soon create equivalent code in, say, Fortran77 or Ansi C. Also, because what
we are coding is simple, there is no need for the elaborate (and laborious to learn) fea-
tures of, say, Fortran95 or C++. Next we encapsulate the code in Python functions using
the f2py tool, and slot them into the Python program. With a little experience, we can
achieve speeds comparable to that of a program written fully in, say, Fortran95.
A comprehensive treatment of Python and its various branches would occupy several
large volumes and would be out of date before it reached the bookshops. This book
is intended to offer the reader a starting point which is sufficient to be able to use the
fundamental add-on packages. Once the reader has a little experience with what Python
can do, it is time to explore further those areas which interest the reader.
I am conscious of the fact that I have not even mentioned vitally important concepts,
e.g., finite-volume methods for hyperbolic problems,6 parallel programming and real-
time graphics to name but a few areas in which Python is very useful. There is a very
large army of Python developers working at the frontiers of research, and their endeav-
ours are readily accessed via the internet. Please think of this little book as a transport
facility towards the front line.
pursue the pundits’ policy. Please save your energy, sanity etc., and read Appendix A,
which I have quite deliberately targeted at novices, for the obvious reason!
Admittedly, there is an amount, albeit slight and low-level, of hassle involved here.
So what’s the payoff? Well, if you follow the routes suggested in Appendix A, you
should end up with a system which works seamlessly. While it is true that the original
Python interpreter was not terribly user-friendly, which caused all of the established IDE
purveyors to offer a “Python mode”, the need which they purported to supply has been
overtaken by the enhanced interpreter IPython. Indeed, in its latest versions IPython
hopes to surpass the facilities offered by Matlab, Mathematica and the Python-related
features of commercial IDEs. In particular, it allows you to use your favourite editor,
not theirs, and to tailor its commands to your needs, as explained in Appendix A and
Chapter 2.
2 Getting Started with IPython
This sounds like software produced by Apple®, but it is in fact a Python interpreter on
steroids. It has been designed and written by scientists with the aim of offering very fast
exploration and construction of code with minimal typing effort, and offering appro-
priate, even maximal, on-screen help when required. Documentation and much more is
available on the website.1 This chapter is a brief introduction to the essentials of using
IPython. A more extended discursive treatment can be found in, e.g., Rossant (2015).
In this chapter we shall concentrate on notebook and terminal modes, and we assume
that the reader has set up the environments as described in Sections A.2 and A.3. Before
we get to realistic examples, I must ask for the impatient reader’s forbearance. Tab com-
pletion, Section 2.1, is an unusual but effective method for minimizing key-strokes, and
the introspection feature, Section 2.2 shows how to generate relevant inline information
quickly, without pausing to consult the manual.
While using the IPython interpreter, tab completion is always present. This means that,
whenever we start typing a Python-related name on a line or in a cell, we can pause
and press the tab key, to see a list of names valid in this context, which agree with the
characters already typed.
As an example, suppose we need to type import matplotlib.2 Typing itab re-
veals 15 possible completions. By inspection, only one of them has second letter m, so
that imtab will complete to import. Augmenting this to import mtab shows 30 pos-
sibilities, and by inspection we see that we need to complete the command by import
matptab to complete the desired line.
That example was somewhat contrived. Here is a more compulsive reason for using
tab completion. When developing code, we tend, lazily, to use short names for vari-
ables, functions etc. (In early versions of Fortran, we were indeed restricted to six or
eight characters, but nowadays the length can be arbitrary.) Short names are not always
meaningful ones, and the danger is that if we revisit the code in six months, the intent of
the code may no longer be self-evident. By using meaningful names of whatever length
is needed, we can avoid this trap. Because of tab completion, the full long name only
need be typed once.
2.2 Introspection
IPython has the ability to inspect just about any Python construct, including itself, and
to report whatever information its developers have chosen to make available. This fa-
cility is called introspection. It is accessed by the single character ?. The easiest way to
understand it is to use it, so you are recommended to fire up the interpreter.
Which mode, terminal or notebook, should one use? Beginners should start with ter-
minal mode, as described in Section A.3, thus removing one level of complexity. This
persists throughout this chapter until Section 2.5, where the code snippets are extremely
short. If you choose to use terminal mode, type ipython followed by a ret on the com-
mand line. IPython will respond with quite a lengthy header, followed by an input line
labelled In [1]:. Now that you are in IPython, you can try out introspection by typing
? (followed by ret) on the input line. (Note that within IPython terminal mode the ret
actually executes the command in the current line.) IPython responds by issuing in pager
mode3 a summary of all of the facilities available. If you exit this, then the command
quickref (hint: use tab completion) gives a more concise version. Very careful study
of both documents is highly recommended.
IPython notebook users need to use slightly different commands. After invoking the
notebook, see Section A.2.2 for details, they will be confronted with an unnumbered
single-line blank cell. Now they can try out introspection by typing ? on the input line.
Typing ret at this point merely adds a new line to the cell. In order to execute the
command(s) in the cell one needs to add either shift+ret (which also creates a new cell
below the current one), or ctl+ret which just executes the command(s). The output, the
lengthy facilities summary, appears in a scrollable window at the bottom of the screen.
It can be killed by clicking on the x-button at the top right of the window. The command
quickref (hint: use tab completion) followed by ctl-ret gives a more concise version.
Again very careful study of both documents is highly recommended.
However, scientists are impatient folk, and the purpose of this chapter is to get them
up and running with the most useful features. Therefore, we need to type in some Python
code, which newcomers will have to take on trust until they have mastered Chapters 3
and 4. Again, depending on whether you are operating in notebook or console mode,
the procedures differ slightly.
Notebook users should type each boxed line or boxed code snippet into a cell. They
can then execute the code via ctl+ret or shift+ret. Readers using terminal mode
3 This is based on the Unix less facility. To use it effectively you need know only four commands:
should type in, line by line, boxed lines or code snippets and enter each line separately
using the ret key.
For example, please type in
a=3
b=2.7
c=12 + 5j
s=’Hello World!’
L=[a, b, c, s, 77.77]
4 Note that in the code snippet there is no multiplication sign (*) between 5 and j.
5 For the sake of brevity, we shall not distinguish between a line in terminal mode and a one-line cell in
notebook mode.
14 Getting Started with IPython
2.3 History
If you look at the output from the code in the previous section, you will see that IPython
employs a history mechanism which is very similar to that in Mathematica notebooks.
Input lines are labelled In[1], In[2], . . . , and if input In[n] produces any output, it
is labelled Out[n]. As a convenience, the past three input lines/cells are available as
_i, _ii and _iii, and the corresponding output lines/cells are available as _, __ and
___. In practice though, you can insert the content of a previous input line/cell into the
current one by navigating using ↑ (or ctl-p) and ↓ (or ctl-n), and this is perhaps the
most common usage. Unusually, but conveniently, history persists in terminal mode. If
you close down IPython (using exit) and then restart it, the history of the previous
session is still available via the arrow keys. There are many more elaborate things you
can do with the history mechanism, try the command history?.
The IPython interpreter expects to receive valid Python commands. However, it is very
convenient to be able to type commands which control either the behaviour of IPython
or that of the underlying operating system. Such commands, which coexist with Python
ones, are called magic commands. A very long very detailed description can be found
by typing %magic in the interpreter, and a compact list of available commands is given
by typing %lsmagic. (Do not forget tab completion!) Note that there are two types of
magic, line magic, prefixed by %, and cell magic, prefixed by %%. The latter is relevant
only to notebook mode. You can get very helpful documentation on each command by
using introspection.
Let us start by considering system commands. A harmless example is pwd, which
comes from the Unix operating system where it just prints the name of the current
directory (print working directory) and exits. There are usually three ways to achieve
this in the IPython window. You should try out the following commands.
!pwd
Nothing in Python starts with a “!”, and IPython interprets this as the Unix shell com-
mand pwd, and produces the ASCII answer.
%pwd
Nothing in Python starts with a “%”, and IPython treats this as a line magic command,
interpreting it as the shell command. The u indicates that the string is encoded in Uni-
code, which enables a rich variety of outputs. Unicode is mentioned briefly in Section
A.3.1.
pwd
2.5 IPython in Action: An Extended Example 15
Here is a subtle, but useful, feature. For line magic commands, the % prefix is not al-
ways necessary, see the discussion of %automagic below. The interpreter sees no other
meaning for pwd and so treats it as %pwd.
pwd=’hoho’
pwd
pwd
Now that pwd has no other assignment, it works as a line magic command.
%automagic?
If %automagic is on, as it is by default, the single per cent sign (%) which starts all line
magic commands, can be omitted. This is a great convenience, provided one remembers
that one is dealing with a magic command.
Magic cell commands start with two mandatory per cent signs. They operate on entire
cells, and can be extremely useful, see, e.g., the next section.
For the rest of this chapter we present the first part of an extended example, in order to
show the effectiveness of magic commands. The second part is the example, in Section
3.9, where we consider how to implement arbitrary precision real arithmetic via frac-
tions. There is an issue with fractions, e.g., 3/7 and 24/56 are usually regarded as the
same number. Thus there is a problem here, to determine the “highest common factor”
of two integers a and b, or, as mathematicians are wont to say, their “greatest common
divisor” (GCD), which can be used to produce a canonical form for the fraction a/b.
(By inspection of factors, the GCD of 24 and 56 is 8, which implies 24/56 = 3/7 and no
further reduction of the latter is possible.) Inspection of factors is not easily automated,
and a little research, e.g., on the web, reveals Euclid’s algorithm. To express this con-
cisely, we need a piece of jargon. Suppose a and b are integers. Consider long division
of a by b. The remainder is called a mod b, e.g., 13 mod 5 = 3, and 5 mod 13 = 5. Now
denote the GCD of a and b by gcd(a, b). Euclid’s algorithm is most easily described
recursively via
gcd(a, 0) = a, gcd(a, b) = gcd(b, a mod b), (b 0). (2.1)
Exploring the Variety of Random
Documents with Different Content
PLEDGED.
By Katharine Tynan, Author of "A Daughter of Erin," Etc.
CHAPTER XVI.
"GOOD-BYE, SWEETHEART."
Beside the Wishing Well stood Anthony Trevithick, pale and
moody. His eyes were on the ground, and an old
childish habit of biting his nails when he was perplexed
or in trouble had come back to him.
"I beg your pardon," said Lord Glengall at his elbow. "I
have returned for some things Miss Graydon left behind her."
"These?" asked the young fellow, pointing with his foot to the little
heap of trinkets on the moss. But even in his anger he blushed for
the unhappiness of the position.
Lord Glengall stooped and picked up the things, and stuffed them
into one of the pockets of his rough coat. He turned as if to go away.
Then he hesitated an instant and came back.
"There is no reason why we should be enemies," he said, advancing
a step nearer.
"No?" replied Anthony Trevithick, lifting his moody eyes. "That
depends."
"On what, sir?"
"On—a great many things," stammered the young man.
"You mean on whether I am prepared to stand aside and to sacrifice
everything that you may have your will. I know the state of affairs,
you see."
"I meant to seek you out and tell you, Lord Glengall. I ought to say,
perhaps, that Miss Graydon is without reproach in this matter."
"Neither of us is likely to wrong her in our thoughts, I hope," said
Lord Glengall. "The question is, whether you are without reproach."
"By what right——" began the younger man.
"Hush!" said the other, with a dignity that was more compelling than
his words. "We are speaking as man to man. Miss Graydon has told
me something of how affairs lay between you and her, but not all.
Why did you leave her in the first instance in the position of a half-
engaged girl?"
"Are you her ambassador?"
"She is dearer to me, I dare swear, than she is to you, though you
will not believe it. There is no use in beating about the bush. If I
think you can make her happier than I can, I am prepared to give
her back her promise."
"Lord Glengall!"
A gesture silenced the words on his lips.
"Don't say anything, please. If I do it, I do it for her. And I shall only
give her up to you if I am sure you are worthy."
"I don't say I am worthy, but I have a fairly clean record. As for that
matter, I will explain. I was unwise, but I was not altogether to
blame. My mother has a greatly loved young cousin. She has been in
the house with us since her mother died some years ago. It was a
scheme of my mother's that we should marry, though it was not
openly expressed. I did not oppose it. I had no idea what love
meant till I saw Pamela; but I had fetched and carried for Lady Kitty.
Probably a great number of people thought we were engaged; and it
seemed to me that I ought to set the matter straight before I was
formally engaged to Pamela."
"It would have been better to have let Pamela alone till you were
quite free."
"Yes, I know, but——"
"There; you are young. You can't be expected to be as deliberate as
an older man. You meant to act straight by her?"
"I meant to come back in a week a free man. When I was called
away to my uncle's sick bed, my mother made me promise not to
speak, not to try to clear up things with Lady Kitty, till I returned. I
did write to Mr. Graydon, but the letter never reached him." He
blushed hotly and paused.
"Yes, I know," interrupted Lord Glengall. "When you came back?"
"When I came back, I found—Pamela engaged to you, and my
cousin engaged to a great friend of mine. As it proved, she had
never thought of me in that way; but her affection for my mother
prevented her from speaking out."
"You should have written again to Mr. Graydon. You made Pamela
unhappy."
"I thought he had not written because I said I would come as soon
as I could. Then I was kept week after week, till the time turned into
months. I am deeply sorry that I caused her unhappiness."
"This is the truth, the whole truth, and nothing but the truth?"
"It is absolutely the truth, and nothing else."
"Very well, Sir Anthony, I believe you. If you had not been straight, I
should have held her to the letter of her bond against you and the
world, even against herself. Now—in her heart she has chosen you,
and you are a fitter mate for her than I—I resign her to you."
"Lord Glengall!"
"I do not ask your thanks, sir. Make her happy—that is all. For the
rest, I have one word of advice for you."
"Whatever it is, I shall act upon it."
"Go back to-night to England."
"Without a word to Pamela?"
"Let her be. I will say what is necessary. You will have to win her
again, young sir. She is not the girl to change her lovers like her
frocks."
"Perhaps you are right, sir," with hesitation.
"Go," said Lord Glengall, waving him away, "go! If you speak to her
in her present mood, you will be sorry. Let her be free of both of us
for a while."
"You, too, will leave her?"
"I shall leave her till all this is forgotten. It will be nothing new for
me to set out for the ends of the earth at an hour's notice."
"You are, as Pamela says, the best man living."
"Stop!" said Lord Glengall, with a gesture as if he could not endure
the praise. "Good-bye!"
"Good-bye," repeated Sir Anthony, turning away.
Several times as he went homeward Lord Glengall stooped to pat the
shaggy coat of the terrier who still trotted by him.
Pointing with his foot to the little
heap of trinkets.
"You don't know poetry, old fellow," he said once aloud, "but there
was a poet named Shakespeare who wrote something about people
coming back 'to push us from our stools.' I am not good at
remembering poetry; but that young gentleman we have just left
has come back to push us from our stools—to push us from our
stools."
The dog, as if he understood, thrust a sympathetic nose into his
companion's hand.
When Lord Glengall reached Carrickmoyle, he went straight to Mr.
Graydon's room. Mary was sitting by her father, stitching a piece of
fine white stuff in the twilight.
"Ah! Glengall," said the invalid briskly. "Have you come in to smoke a
last pipe with me? Come and tell me what prices were like at the fair
to-day. Run away, Molly child, and rest your eyes, and let Glengall
have your seat."
The two men lit up soberly, and smoked away for a while, discussing
prices and cattle and crops in a desultory fashion.
At last Lord Glengall knocked out the ashes from his stumpy clay
against the top bar of the grate, and stuffed the pipe into his pocket.
"I wanted to talk to you about Pam, Graydon," he said.
"What about Pam?"
"Only that I did the child an injustice in wanting to marry her. I am
too old."
"Does Pam say this? Are you speaking for her?"
"Poor little Pam! There were some love-passages, Graydon, between
her and your pupil Trevithick."
"I guessed as much, but how far the thing went I have no idea. I
don't believe in probing into those things, Glengall. It is better to let
them die."
"Had you any idea that the young fellow might possibly ask for her?"
"I hoped so once, not because it would be a good marriage for Pam,
or anything of that sort, but because I thought him a good lad, and I
believed in his father's son. I was disappointed that he turned out so
different from my expectations."
"Would you be surprised to hear that he wrote to you about Pam
immediately after he left, and that his mother intercepted the
letter?"
"His mother!"
"Yes; she had other views for him."
"I wonder why she came here, why she troubled our peace, and
forced her hospitality on Pam, who didn't want it?" said Mr. Graydon
musingly.
"To make a parting between the lad and Pam more certain. She told
Pam he was engaged to his cousin; and in other ways made the
child's visit miserable."
"My poor Pam! I remember she hated to go."
"I am sorry the boy has such a mother."
"Yet I remember her a very noble-looking girl. I don't think she was
made for mean things."
"Ah! well, we can let her be. She is sufficiently punished, poor
woman, by her son's scorn. That must be a terrible thing to endure."
"And she is a proud woman."
"However, Graydon, we are not concerned with her. The state of the
case is this: The young people were in love with each other, and
were parted by a fraud. Under a total misapprehension, Pamela has
engaged herself to me. Now that the misapprehension is removed,
what is the clear course for me to take?"
"I should ask Pamela, Glengall."
"Pamela is at this moment in a mood in which it would not be safe to
take her at her word. The only thing for me to do is to step down
and out."
"Glengall!" said Mr. Graydon, laying a hand on his.
"Don't pity me just now, Graydon. Frankly, I'm not equal to it."
"Have you told Pam?"
"I shall tell her. Afterwards I shall go away till the nine days' wonder
is forgotten."
"Glengall, I wish this had not happened."
"There is one way in which you can atone to me for its bitterness—I
don't mind confessing to you that it is bitter."
"And that way?"
"You must borrow from me what will take you abroad. You must; it
is for their sakes."
"Very well; if there is no other way. I shall repay you, I hope."
"You have plenty of time before you to grow rich in. When you come
back next spring, you must finish your magnum opus."
Mr. Graydon rubbed his hands in boyish cheerfulness.
"I shall feel equal to tackling it after a change. I'm afraid I've been
vegetating, and the mosses and mildew have grown upon me. You
have lived, Glengall, while I was growing into a worthless old block."
"It is you who have lived," said Lord Glengall. "You have lived
naturally. When I die, it is the end of my line, and I shall have no
one to close my eyes."
When he found Pam in the drawing-room alone, a little later, he
drew her to him, and kissed her hair where it clustered over the
white forehead.
"I have brought your pretty things, Pam," he said, fumbling in his
pocket.
"And you have forgiven me?"
"I have forgiven you, dear."
He fastened the little chain about her neck and the bracelet on her
wrist.
"You will wear them for me, Pam?" he said. "I should not know what
to do with them."
"And my ring?" said Pam, wondering.
"I have taken back the ring. You are free, Pam; free as air."
"You are free, Pam; free as air."
"But I don't want to be free."
"You did yesterday, Pam, and you will to-morrow. I have seen Sir
Anthony, Pam. He is guiltless, and will come again."
"I do not want him to come," cried Pam with a great sob.
"I sent him away because I was afraid if he came to you now you
would make him and yourself unhappy. He hated to go, but he went.
He will come again. You will be good to him, Pam, because you love
him. Now, good-bye, my dear. I shall come back when you are
married."
Pamela's hands were over her eyes, and she was crying quietly.
"Another thing, Pam," he said. "I have arranged with your father. He
is to winter abroad."
"Sylvia will see to that," she answered. "Miss Spencer has made it
easy for her. At least, we need not take that from you."
"You have given me great happiness," he repeated. "And now, good-
bye, my dear, good-bye."
A day or two later Carrickmoyle was startled by the news that Lord
Glengall had sailed for Australia.
CHAPTER XVII.
"THOUGH 'TWERE TEN THOUSAND MILE."
"I wish something would happen," said Sylvia; "it is the longest
summer I have ever known."
Sylvia was wearing black for Miss Spencer, who had passed away
peacefully a few weeks after that talk with Pamela. When the legal
formalities were completed, Sylvia would be châtelaine of
Dovercourt; but her interest in her inheritance seemed very slight.
"By-and-by," she had said, "I shall be glad to know that I have
money to do things with; but just at present I can only remember
what it is that has made me rich."
"I thought you were going to
marry him, Bridget."
"Why not have Mr. Baker or Mr. St. Quintin to tea quietly?"
suggested Pam. "I am sure they are longing to come, and they
would cheer you up."
But Sylvia would not. She preferred to wander from the house to the
garden with the dogs at her heels, or to stray from one room to
another, having a desultory chat with her father, who was now up
and about, or with Mary, cheerfully sewing her bridal clothes, usually
ending up with a visit to Bridget in the kitchen.
Bridget quite agreed with Sylvia about the dulness of the house, and
suggested the same remedy for it as Pamela had done.
"Have a bit of company, child," she said. "Sure, her that's gone (the
heavens be her bed!) 'ud be the last to grudge the young what's
natural to the young, let alone that I hear young Mr. St. Quintin's
that mopy that they say 'tis to horse-racin' he's took, wid the design
of breakin' his neck by way of divarsion."
"Don't talk such nonsense, Bridget," said Sylvia languidly. "The horse
is not born that could unseat Mr. St. Quintin. He can stick on like
grim death. But I don't feel that company, such company as I could
get, would be any good to me. I don't like young people, Bridget."
"Well, sorra such a house I ever was in," said Bridget, scandalised.
"Never mind, Bridget dear," said Sylvia, who had temporarily lost her
taste for sharp argument with Bridget. "I suppose I was born old."
"Listen to her," cried Bridget, "an' she wid the lightest feet, aye, an'
the purtiest face in the barony! Between you and Miss Pamela, me
heart's fairly bruk. There's Miss Pamela, that ought to be goin' to be
married a week from next Tuesday, goin' round as mopy as a
chicken wid the pip. I never seen such goin's on anywhere I was."
"It certainly is time," said Sylvia again, "that something should
happen, and, short of marrying myself, Bridget, I'll do anything to
bring it about."
"Indeed, then Mr. St. Quintin's a pleasant young gentleman," said
Bridget, broadly smiling, "though an imp of mischief. 'Tis meself'll
not forget in a hurry how he whipped the steps from undher Grady
whin he was pickin' the morello cherries, an' never purtended he
heard him bawlin' melia murther, an' the ould rogue, as he was
contrivin' to slip down by the trunk, caught by a twig in his breeches
an' held there! As I said to Mr. St. Quintin, I hoped he thought then
on poor Mary that's gone, that often he made suffer, the crathur!"
"I thought you were going to marry him, Bridget," said Sylvia, with
the same languid interest.
"Och, then, heaven forgive you, Miss Sylvia. Sure them was only my
jokes. Not but what he axed me. 'The mischief bother you, man,'
says I. 'Is it havin' me commit murther you'd be? Why, sure I
couldn't keep me hands off you if I was lookin' at you every day, an'
then I'd be tried an' hung for it, maybe.'"
"Well, I'm glad you're not going to marry him under the
circumstances," said Sylvia. "But, all the same, it is time some of us
made a stir."
And even then one thing that was to disturb the current of their lives
was on its way.
The very morning after Sylvia's conversation with Bridget there was
a large square envelope for Mr. Graydon, which somewhat exercised
his youngest daughter's imagination.
"Come here, dad," she said, when at last he arrived at the breakfast-
table. "I've been longing for something to happen, and I believe this
is really a happening at last."
"It is my uncle's writing," said Mr. Graydon, as he took the letter and
opened it. As he read it his face grew graver and graver.
"Poor old Uncle Charles!" he said, when he had finished. "His boy is
dead."
Lord Downshire's letter was very characteristic:—
"My dear Archie,—I will not say you have scored again, but at least I
have failed with the last card I held against you. My boy is dead. I
don't ask for your sympathy or your pity. You, with your healthy
girls, cannot appreciate what I suffer. I am racked in the spirit and
the body, and I shall be very glad to leave a world that has lost
savour for me. I heard indirectly that you were ill after you had been
here; but, you see, you have recovered, and it is my boy that is
dead. You are my heir now, and I am too sick of it all to make
another attempt to frustrate you. And there is no use continuing in
enmity against you, so I shall make you an allowance proportionate
to the condition of my heir. I shall not ask to see you, but Messrs.
Lees and Saunders, of Lincoln's Inn—you will remember Saunders;
Lees died last year—have my instructions."
Mr. Graydon put the letter into his pocket when he had read it.
"Something has happened, Sylvia," he said sorrowfully. "I am Lord
Downshire's heir once more; and yet I would a thousand times
rather be as I was, and the old man's little son living."
But the happenings of the day were not over.
Sylvia, going her pilgrimage to Miss Spencer's new grave, was aware
of a tall young figure, which had something familiar about it,
swinging along towards her. Presently she recognised Anthony
Trevithick.
"Miss Sylvia," he said, "I am so glad I met with you. I want to see
Pamela."
"Pamela!" with oddly upraised eyebrows.
"Yes—Pamela. I have stayed away as long as I could. I promised
Lord Glengall I would give her time."
"Oh! that is how it is, is it?"
"Yes; didn't you know?"
"I guessed, of course, but Pam is not the old Pam. She has been as
solemn as an owl, and as secretive, ever since.... When was it?... I
really think it began about the time of your going away. She used to
be the best of good company."
"What is this for, Miss Sylvia?" said the young man, touching her
black frock.
"Ah! You do not know. Miss Spencer died a month ago."
"I am sorry," he said, with a sympathy which at once made Sylvia his
friend.
"Does Pam know you are coming?" she asked.
"No. I was afraid to announce myself. Perhaps she will show me the
door."
"Perhaps she won't, Sir Anthony. She's fond of you, you see."
"Oh, Miss Sylvia!" cried Anthony Trevithick, flushing delightedly
through his tan.
"Oh, yes! she's fond of you. I'm not going to talk about her secrets,
but I know how it is. I knew all along. That is why I was so vexed
with her—when—— Never mind. You want to see Pamela, then?
Well, just wait for me a minute outside this gate. I will come back
with you then, and find Pamela for you."
"You are awfully good."
"Perhaps I'm glad to get rid of Pam. She's prettier than I am, though
some people don't think so. Perhaps I'm afraid of her stealing my
admirers."
"I believe it is only your goodness to me."
"And to Pam. She's not the same Pam she was a year ago. If you
make her like her old self, I shall forgive you even that you left us
forlorn and unsquired at that famous festivity for which you should
have returned."
"Oh! Miss Sylvia, I shan't believe that."
She did not try Anthony Trevithick's patience by keeping him waiting
long at the churchyard gate. She was gone only a minute or two
before she returned, her basket empty of its flowers, and her face,
which had gained so much in character and sweetness during the
year, a little overshadowed.
When they reached Carrickmoyle, she brought Anthony Trevithick
through the sunny hall where the door stood, as ever, hospitably
open, and into the big drawing-room. "Stay here till I find Pam," she
said. She went upstairs two steps at a time in the boyish way he
remembered. He listened with a smile on his face till the sound of
the footsteps died away. Then he began to walk up and down
nervously.
Pam sat in the window of her own little room with her chin in her
hands, gazing over the summer-dark landscape, her air listless, and
her eyes apathetic.
"It is lonely, Sylvia," she said, scarcely turning her head as her sister
entered.
"You never used to find it so," said Sylvia. "I remember the time
when Carrickmoyle held all the delights for you."
"That was when we were little girls in short frocks, and led poor Mick
into scrapes."
"Many a year ago," said Sylvia. "When you struck Anthony Trevithick
with the sun-bonnet that was intended for the red cock——"
Pamela's heightened colour assured Sylvia of what she wanted to
know.
"Pam," she said, "why don't you make it straight with Anthony
Trevithick?"
"How do you know there is anything to make straight?"
"Rubbish!" said Sylvia, with quiet scorn.
"Oh, Sylvia!" said Pamela, "you don't understand. I am tired of love
and lovers. I only want to be let alone. I have suffered too much."
"If you have, it's your own fault. You'd no business to take poor dear
Glengall when you were in love with someone else, though how you
could look at others in the same day with Glengall fairly bothers me.
And now, why don't you write and ask Anthony Trevithick to come
back?"
"I don't want him to come back."
"Yes, you do; you're crying your eyes out for him every night. Yes,
you are. And why you let all this muddle go on without doing
anything to prevent it I don't know. I could shake you, Pam!"
"What would you have done, Sylvia?"
"Well, supposing I was in love with a man and knew him to be in
love with me, and supposing he went away and didn't write, I'd
never think anything except that the letter was lost. If I could get at
him, I'd write and ask him what it meant. If I couldn't, I'd go on
believing in him, maybe till I was old and grey, and till I died, as
some have done—if I really loved him, mind you."
"Perhaps you are right, Sylvia."
"There's no doubt about it, Madam Faint-Heart."
"But come," she said, after a benevolent scrutiny of Pamela; "come,
you look very nice, unless you'd like to put on the pink sun-bonnet.
Anthony Trevithick is in the drawing-room."
"Sylvia!"
"Yes, I know I ought to have mentioned it before, instead of talking
nonsense. The poor young man's on tenter-hooks."
"Sylvia! I can't go down."
"Yes, you can. You shall, even if I have to use force."
"Very well, Sylvia," said Pam, rising and trembling a little.
"Come, don't think about it. Do it quickly, as we used to take our
cod-liver oil long ago. Let us run down the stairs. There, you poor
little thing! your hands are cold. The run will warm them."
And, half-resisting, Pamela was pulled by force down the stairs.
Nevertheless, she entered the room with her head high.
"How do you do, Sir Anthony?" she began.
"Ah, Pam darling!" cried the young man, coming to meet her. "Don't
give me any more cold words or cold looks. I haven't deserved
them, and if you've nothing else for me I shall go away for ever."
"No, surely," said Pam, and her sweet voice had a little surprise in it.
"You didn't really deserve any blame at all."
"But you did, for I asked you to trust me, Pam. I asked you to trust
me, and your faith was brittle."
"So it was," said Pam.
"Well," said Sylvia, as she went out and closed the door. "It is plain
these recriminations are not meant for me. Heigho! I wish Mr. Baker
would come along just now, that I might have the satisfaction of
refusing him. It is easy to see that Glengall is as completely
forgotten as if he had never existed."
No one could say that Mr. Graydon's youngest daughter was not
loyal to the absent.
CHAPTER XVIII.
A PROPOSAL.
Pamela Graydon had been Pamela Trevithick for three years, when
one day in late summer Sylvia, still Sylvia Graydon, was entertaining
a visitor in her London drawing-room.
It was Lord Glengall, a shade greyer, a shade leaner, but looking well
nevertheless, and brown with southern suns.
"And so," he said, "we shall travel back to Ireland together."
"It will be a delightful and unexpected pleasure to have your
company."
"You are glad to return, Sylvia?"
"Glad! It is no word for it. I am hungry for the velvety wind that
blows across the mountains. I am so tired of these glaring streets, of
parties, and dinners and luncheons, and functions of all kinds."
Lord Glengall laughed.
"To tell you the truth, I am amazed and amused to find your father
in the midst of it all."
Half-resisting, Pamela was pulled by force.
"Papa! Oh, papa is the veriest Piccadilly lounger. He has returned to
it all as freshly as if he had never left it. He discovered troops of old
friends—without a misgiving—as soon as ever he came in for the
title."
"He doesn't pine for Carrickmoyle?"
"Now and again. When the desire becomes very strong, he and I slip
away to Euston some evening, forgetting all our engagements, and,
for a few days, our new circumstances, at Carrickmoyle, where
Bridget cooks our chops and makes us potato-cakes just as of old."
"I am glad to hear Bridget is still to the fore."
"She is not a day older."
"She never carried out her threat of marrying my gardener?"
"Mr. Grady is still a widdy-man, as they used to say in the dear
country."
"But to return to your father. The magnum opus has become an
accomplished fact. You see, I haven't been so far out of the world as
not to have heard that."
"Yes. It has been a great success. He is as much in request at
learned societies and conversaziones as he is in fashionable drawing-
rooms. To think of the years he vegetated at Carrickmoyle!"
"Happy years, Sylvia."
"I could hardly hope for happier."
"He will be in soon, Sylvia?"
"About half-past five," consulting a little watch fastened to her gown.
"You can endure my company till then."
"I shall try to. But am I not keeping you from afternoon calls or
something? I saw a carriage at the door as I came in."
"I have sent it away. I was rejoiced to do it. Papa will be simply wild
with delight at your falling from the clouds like this."
"He hasn't forgotten me, then?"
"How should he? The only drawback about Carrickmoyle has been
that we could see from it the cold chimneys of Glengall."
"Ah! we shall warm them," said Lord Glengall, beaming at her. "We
shall have fine jinks if only you and your father will spend six months
of the year at Carrickmoyle. I am no Londoner, and never shall be.
But I shall be able to endure six months of solitude if I know I am
going to have you for the remainder of the year."
"You will not long be left solitary. You cheated the country the last
time by disappearing again before it had had time to rejoice over
you. Your return will flutter the dovecotes for thirty miles around."
"You are very kind, Sylvia," said Lord Glengall simply. "But you have
not told me half the news," he went on. "How is Molly?"
"Flourishing. Mick has got his company. He wouldn't leave the
service on any consideration, and I think he was right. They are as
much in love with each other as ever; and they have a beautiful
boy."
"Ah! that is right. Molly deserved to be happy."
"She did, and so did Mick. Mick is a dear old fellow."
"And Pam, Sylvia?"
There was no consciousness in his voice.
"Pam, too, is a success. She has been a beauty for three seasons,
strange to say."
"And it is a happy marriage?"
"Perfectly happy. They are ideally well suited."
"I am glad of that. How does Pam get on with her mother-in-law?"
"Fairly well, I believe. Lady Jane keeps herself to herself, which is
lucky for Pam. I never took to that lady. But she is devoted to the
heir. She wouldn't strike you, somehow, as a grandmotherly person,
but it is so."
"There is an heir?"
"Yes; he is two years old, and he has a baby sister of seven
months."
"Ah! how you young people have been making history since I left. I
shall not know this new world of your making."
"You find me changed?"
"Lovelier, Sylvia."
"It is nice to have you say that."
"Still greedy for conquest, even though it is only an old fogey?"
"Ah!"—with more intensity than he thought the occasion demanded
—"you never can be that!"
"You are always kind, little girl. When I look into your eyes, I fancy it
is the old Sylvia I am talking to, and not a fine lady."
"It is the old Sylvia."
"The Sylvia I knew would never have worn this"—touching a fold of
her dress.
"She would, if she could. It is only a Paris tea-gown. She was
happier in the prints at sixpence a yard from Guirk's shop in
Lettergort."
"Happier, Sylvia? What have you been doing with yourself since?"
"Growing old and faded with trying to occupy several houses at once
and doing a great many things I detest."
She laughed at him from where she sat in her youth and beauty, and
he laughed in answer.
"Where are the lads who used to be in love with you?"
"All married, except Algy St. Quintin; but he has long given up
asking me. We are good comrades."
"No more than that, Sylvia?"
"No more than that. I wouldn't lose sight of him for anything. He is
just the same imp of mischief, as Bridget used to call him. His
coolness is phenomenal, and his impudence so deliciously
incongruous with his cherubic boy's face."
"There is no one else, Sylvia?"
"There is no one else."
"Ah! you are so hard-hearted, child. Or is it that you will stay with
your father?"
"Not altogether that. I've seen no one here I would marry."
"Yet you have met all sorts and conditions of men."
"All sorts and conditions, but not the right one."
"The right one will come."
"He might come—he may have come, and not have found me the
right woman."
She looked at him an instant; then she suddenly blushed hotly, and
her eyes fell and rested on the jewelled fingers in her lap. So full
was her attitude of yielding and submission that it might well make
the heart of a lover leap.
A sudden, bewildering idea came to the man before her. For an
instant he was dazed with the shock of it. Then he stood up and
paced the room in great agitation.
"Sylvia," he said at last, pausing before her where she still sat, a
lovely image of submission, "Pamela was right when she did not
marry me."
"She was right because she did not love you."
"How could she love me? I might have been her father."
"That is no reason. Love does not take count of such things."
"Ah, Sylvia! What has love to do with grey hairs?"
"If there is love, they are better than gold."
"Sylvia, do you know what madness you are putting into my head?"
"I cannot know unless you tell me."
Sylvia's eyes were raised to his with a flash of the old audacity.
"Perhaps I dare not tell you."
"Ah, do!"
"If I were a young man and you would do it, you might turn this
work-a-day earth to Paradise for me."
"And why not now?"
He made a step towards her.—p. 552.
"Ah! child, you do not know what you are saying. What could you, a
beauty and an heiress, see in me?"
"I am glad I am beautiful to you. But why should that and the other
things stand between me and my happiness?"
"Your happiness, Sylvia?"
"Ah, yes! You wouldn't see it, but I always thought there was no one
in the world like you. You chose Pam before me, and even then I
accepted your will, but I loved you still."
"I chose Pam because she was unhappy, because there seemed no
other way. It did not break my heart to give her up, though it was a
blow. It does not hurt me now to hear of her as Lady Trevithick. But
I dare not risk the same thing with you."
"Why?"
"Because it would be so easy to forget my years, and love you with
a young man's ardour, and more than a young man's faith."
"Then why not love me?"
"Ah! Sylvia, it is your kindness, your compassion. I could not endure
to be thrown over now, even though I am well on in my forties."
"I shall not throw you over. Look at me, and you will see."
He looked at her, and made a step towards her.
"Then you will make the world over again for me?"
"And you for me?"
"Ah, Sylvia!"
"Yes. How hard it was to persuade you. There will be lots of people
who will want to marry you once it is known you have come back.
You might have liked someone better than me. And I have waited
for three years."
"You fairy princess, what do you mean by condescending to a
mortal's grey hairs?"
"We shall be so happy, you and I and papa. We shall lead the
country life, though he'll have to come to London now and again for
his serious 'frivolities.' And I shall make you care for me. Now you do
not care for me nearly so much as I do for you."
"You bewilder me, Sylvia."
"Ah! yes, you will care for me. I shall not let you cheat me."
"You talk as if my youth were not flown, you lovely child."
"It is not flown. You do not mean to say you used up your youth
during those hard years that lined your face and sowed grey hairs in
your head? Ah! no, you were saving it up for me."
"It is too incredible!"
"Take time, then, to think, good gentleman," said Sylvia, with
laughter dancing bewitchingly about her mouth; but her eyes were
tender.
"If I take time, all this will take wings like a dream and fly away."
"Then keep it," said Sylvia.
"My life—what remains of it—will be devoted to you."
"It is time you should say that. You have been going after false fires,
while I have been true all the time."
"You to me, Sylvia!"
"I to you. But if I had not almost asked you, you would have left me
to single blessedness. Ah! there is papa's ring. He will be glad."
"He will think it folly, Sylvia."
"Ah! no, he won't. Dear, wise papa, he was always anxious for you
to marry one of his daughters."
THE END
TIRED.
On the weary waves of the world
To and fro
This tired life of mine has been whirled!
In the flow
And ebb of every dangerous tide
My thoughts have drifted far and wide,
As on a bleak and bare hill-side
Drifts the snow.
H. Brooke Davies.
Light through Dull Panes.
A VISIT TO THE EARLSWOOD ASYLUM.
(Illustrated from Photographs by Cassell and Co., Ltd.)
IN HIS OWN
WORKSHOP.
"It must be sad and painful to a visitor," the matron said, "to have a
passing glance at the worst cases, but to live amongst them, as she
had done for eleven years, was full of interest. Nearly all were
capable of some improvement."
A home where everything is done to promote their health and
happiness is, for the weak-minded, a new world. To be taken from
conditions of continual disadvantage, and placed under the charge of
guardians whose first duty is to work and watch for the awakening
of soul and mind, brings hope and comfort into their life. A poor
constitution is often added to the disadvantages of the imbecile; and
in families where their friends cannot constantly protect them they
are often exposed to teasing, and driven into fits of fury, ending in
chronic bad temper, by the mischief or malice of their companions.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com