100% found this document useful (1 vote)
547 views48 pages

IPython Interactive Computing and Visualization Cookbook 1st Edition Cyrille Rossant - The complete ebook version is now available for download

The document provides information about the 'IPython Interactive Computing and Visualization Cookbook' by Cyrille Rossant, which includes over 100 hands-on recipes for high-performance numerical computing and data science with Python. It also contains links to download the book and explore additional recommended ebooks related to data visualization and analysis. The book was published by Packt Publishing in 2014 and covers various topics including interactive computing, data visualization, and machine learning.

Uploaded by

karaaaniseh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
547 views48 pages

IPython Interactive Computing and Visualization Cookbook 1st Edition Cyrille Rossant - The complete ebook version is now available for download

The document provides information about the 'IPython Interactive Computing and Visualization Cookbook' by Cyrille Rossant, which includes over 100 hands-on recipes for high-performance numerical computing and data science with Python. It also contains links to download the book and explore additional recommended ebooks related to data visualization and analysis. The book was published by Packt Publishing in 2014 and covers various topics including interactive computing, data visualization, and machine learning.

Uploaded by

karaaaniseh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Visit https://ebookultra.

com to download the full version and


explore more ebooks or textbooks

IPython Interactive Computing and Visualization


Cookbook 1st Edition Cyrille Rossant

_____ Click the link below to download _____


https://ebookultra.com/download/ipython-interactive-
computing-and-visualization-cookbook-1st-edition-cyrille-
rossant/

Explore and download more ebooks or textbooks at ebookultra.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Python Data Visualization Cookbook 2nd Edition Igor


Milovanovic

https://ebookultra.com/download/python-data-visualization-
cookbook-2nd-edition-igor-milovanovic/

OpenStack Cloud Computing Cookbook Second Edition Kevin


Jackson

https://ebookultra.com/download/openstack-cloud-computing-cookbook-
second-edition-kevin-jackson/

Visualization Analysis and Design 1st Edition Tamara


Munzner

https://ebookultra.com/download/visualization-analysis-and-design-1st-
edition-tamara-munzner/

Visualization Handbook 1st Edition Johnson C.R.

https://ebookultra.com/download/visualization-handbook-1st-edition-
johnson-c-r/
Data Visualization with D3 and AngularJS 1st Edition
Korner

https://ebookultra.com/download/data-visualization-with-d3-and-
angularjs-1st-edition-korner/

The Visualization Handbook 1st Edition Christopher R.


Johnson

https://ebookultra.com/download/the-visualization-handbook-1st-
edition-christopher-r-johnson/

Fractals Visualization and J Fourth edition Part 1 Reiter

https://ebookultra.com/download/fractals-visualization-and-j-fourth-
edition-part-1-reiter/

Data Analysis and Visualization in Genomics and Proteomics


1st Edition Francisco Azuaje

https://ebookultra.com/download/data-analysis-and-visualization-in-
genomics-and-proteomics-1st-edition-francisco-azuaje/

JavaScript and jQuery for Data Analysis and Visualization


1st Edition Jon Raasch

https://ebookultra.com/download/javascript-and-jquery-for-data-
analysis-and-visualization-1st-edition-jon-raasch/
IPython Interactive Computing and Visualization
Cookbook 1st Edition Cyrille Rossant Digital Instant
Download
Author(s): Cyrille Rossant
ISBN(s): 9781783284818, 1783284811
Edition: 1
File Details: PDF, 8.85 MB
Year: 2014
Language: english
IPython Interactive
Computing and
Visualization
Cookbook

Over 100 hands-on recipes to sharpen your skills in


high-performance numerical computing and data
science with Python

Cyrille Rossant

BIRMINGHAM - MUMBAI
IPython Interactive Computing and
Visualization Cookbook

Copyright © 2014 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the publisher,
except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly
or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies
and products mentioned in this book by the appropriate use of capitals. However, Packt
Publishing cannot guarantee the accuracy of this information.

First published: September 2014

Production reference: 1190914

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78328-481-8

www.packtpub.com

Cover image by Aniket Sawant ([email protected])


Credits

Author Proofreaders
Cyrille Rossant Simran Bhogal
Martin Diver
Reviewers Maria Gould
Chetan Giridhar Ameesha Green
Robert Johansson Paul Hindle
Maurice HT Ling Lucy Rowland
Jose Unpingco
Indexer
Commissioning Editor Tejal Soni
Kartikey Pandey
Graphics
Acquisition Editor Sheetal Aute
Greg Wild Ronak Dhruv
Disha Haria
Content Development Editor
Sriram Neelakantan
Production Coordinators
Melwyn D'sa
Technical Editors
Adonia Jones
Madhuri Das
Manu Joseph
Taabish Khan
Saiprasad Kadam
Pratik More
Nilesh R. Mohite
Komal Ramchandani
Copy Editors
Janbal Dharmaraj Alwin Roy
Deepa Nambiar Nitesh Thakur
Karuna Narayanan
Cover Work
Alwin Roy
Project Coordinator
Judie Jose
About the Author

Cyrille Rossant is a researcher in neuroinformatics, and is a graduate of Ecole Normale


Supérieure, Paris, where he studied mathematics and computer science. He has worked at
Princeton University, University College London, and Collège de France.

As part of his data science and software engineering projects, he gained experience
in machine learning, high-performance computing, parallel computing, and big data
visualization. He is one of the developers of Vispy, a high-performance visualization
package in Python. He is the author of Learning IPython for Interactive Computing and Data
Visualization, Packt Publishing, a beginner-level introduction to data analysis in Python, and
the prequel of this book.

I would like to thank the IPython development team for their support.
I am also deeply grateful to Nick Fiorentini and his partner Darbie Whitman
for their invaluable help during the later stages of editing.

Finally, I would like to thank my relatives and notably my wife Claire.


About the Reviewers

Chetan Giridhar is an open source evangelist and Python enthusiast. He has been invited
to talk at international Python conferences on topics such as filesystems, search engines, and
real-time communication. He is also working as an associate editor at Python editorial, The
Python Papers Anthology.

Chetan works as a lead engineer and evangelist at BlueJeans Network


(http://bluejeans.com/), a leading video conferencing site on Cloud Company.

He has co-authored an e-book, Design Patterns in Python, Testing Perspective, and has
reviewed books on Python programming at Packt Publishing.

I'd like to thank my parents (Jayant and Jyotsana Giridhar), my wife Deepti,
and my friends/colleagues for supporting and inspiring me.

Robert Johansson has a PhD in Theoretical Physics from Chalmers University of


Technology, Sweden. He is currently working as a researcher at the Interdisciplinary
Theoretical Science Research Group at RIKEN, Japan, focusing on computational
condensed-matter physics and quantum mechanics.

Maurice HT Ling completed his PhD in Bioinformatics and BSc (Hons) in Molecular and
Cell Biology from The University of Melbourne, Australia. He is currently a research fellow
in Nanyang Technological University, Singapore, and an honorary fellow in The University of
Melbourne, Australia. Maurice coedits The Python Papers and cofounded the Python User
Group (Singapore), where he has served as an executive committee member since 2010.
His research interests lies in life—biological and artificial life, and artificial intelligence—using
computer science and statistics as tools to understand life and its numerous aspects. His
personal website is http://maurice.vodien.com.
Jose Unpingco is the author of the Python for Signal Processing blog and the
corresponding book. A graduate from University of California, San Diego, he has spent almost
20 years in the industry as an analyst, instructor, engineer, consultant, and technical director
in the area of signal processing. His interests include time-series analysis, statistical signal
processing, random processes, and large-scale interactive computing.

Unpingco has been an active member of the scientific Python community for over a decade,
and developed some of the first video tutorials on IPython and scientific Python. He has also
helped fund a number of scientific Python efforts in a wide variety of disciplines.
www.PacktPub.com

Support files, eBooks, discount offers, and more


You might want to visit www.PacktPub.com for support files and downloads related to
your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
[email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up
for a range of free newsletters and receive exclusive discounts and offers on Packt books
and eBooks.
TM

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's entire library of books.

Why Subscribe?
ff Fully searchable across every book published by Packt
ff Copy and paste, print and bookmark content
ff On demand and accessible via web browser

Free Access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine entirely free books. Simply use your login credentials for
immediate access.
Table of Contents
Preface 1
Chapter 1: A Tour of Interactive Computing with IPython 9
Introduction 9
Introducing the IPython notebook 13
Getting started with exploratory data analysis in IPython 22
Introducing the multidimensional array in NumPy for fast array computations 28
Creating an IPython extension with custom magic commands 32
Mastering IPython's configuration system 36
Creating a simple kernel for IPython 39
Chapter 2: Best Practices in Interactive Computing 45
Introduction 45
Choosing (or not) between Python 2 and Python 3 46
Efficient interactive computing workflows with IPython 50
Learning the basics of the distributed version control system Git 53
A typical workflow with Git branching 56
Ten tips for conducting reproducible interactive computing experiments 59
Writing high-quality Python code 63
Writing unit tests with nose 67
Debugging your code with IPython 74
Chapter 3: Mastering the Notebook 79
Introduction 79
Teaching programming in the notebook with IPython blocks 84
Converting an IPython notebook to other formats with nbconvert 89
Adding custom controls in the notebook toolbar 94
Customizing the CSS style in the notebook 96
Using interactive widgets – a piano in the notebook 99
Table of Contents
Creating a custom JavaScript widget in the notebook – a spreadsheet
editor for pandas 103
Processing webcam images in real time from the notebook 108
Chapter 4: Profiling and Optimization 115
Introduction 115
Evaluating the time taken by a statement in IPython 116
Profiling your code easily with cProfile and IPython 117
Profiling your code line-by-line with line_profiler 121
Profiling the memory usage of your code with memory_profiler 124
Understanding the internals of NumPy to avoid unnecessary array copying 127
Using stride tricks with NumPy 133
Implementing an efficient rolling average algorithm with stride tricks 135
Making efficient array selections in NumPy 138
Processing huge NumPy arrays with memory mapping 140
Manipulating large arrays with HDF5 and PyTables 142
Manipulating large heterogeneous tables with HDF5 and PyTables 146
Chapter 5: High-performance Computing 149
Introduction 149
Accelerating pure Python code with Numba and Just-In-Time compilation 154
Accelerating array computations with Numexpr 158
Wrapping a C library in Python with ctypes 159
Accelerating Python code with Cython 163
Optimizing Cython code by writing less Python and more C 167
Releasing the GIL to take advantage of multi-core processors
with Cython and OpenMP 174
Writing massively parallel code for NVIDIA graphics cards (GPUs)
with CUDA 175
Writing massively parallel code for heterogeneous platforms
with OpenCL 181
Distributing Python code across multiple cores with IPython 185
Interacting with asynchronous parallel tasks in IPython 189
Parallelizing code with MPI in IPython 192
Trying the Julia language in the notebook 195
Chapter 6: Advanced Visualization 201
Introduction 201
Making nicer matplotlib figures with prettyplotlib 202
Creating beautiful statistical plots with seaborn 205
Creating interactive web visualizations with Bokeh 208
Visualizing a NetworkX graph in the IPython notebook with D3.js 211
Converting matplotlib figures to D3.js visualizations with mpld3 215

ii
Table of Contents
Getting started with Vispy for high-performance interactive
data visualizations 218
Chapter 7: Statistical Data Analysis 225
Introduction 225
Exploring a dataset with pandas and matplotlib 229
Getting started with statistical hypothesis testing – a simple z-test 233
Getting started with Bayesian methods 236
Estimating the correlation between two variables with a contingency
table and a chi-squared test 241
Fitting a probability distribution to data with the maximum
likelihood method 245
Estimating a probability distribution nonparametrically with
a kernel density estimation 251
Fitting a Bayesian model by sampling from a posterior distribution
with a Markov chain Monte Carlo method 255
Analyzing data with the R programming language in the
IPython notebook 261
Chapter 8: Machine Learning 267
Introduction 267
Getting started with scikit-learn 273
Predicting who will survive on the Titanic with logistic regression 281
Learning to recognize handwritten digits with a K-nearest
neighbors classifier 285
Learning from text – Naive Bayes for Natural Language Processing 289
Using support vector machines for classification tasks 293
Using a random forest to select important features for regression 298
Reducing the dimensionality of a dataset with a principal
component analysis 302
Detecting hidden structures in a dataset with clustering 306
Chapter 9: Numerical Optimization 311
Introduction 311
Finding the root of a mathematical function 314
Minimizing a mathematical function 317
Fitting a function to data with nonlinear least squares 323
Finding the equilibrium state of a physical system by minimizing
its potential energy 326
Chapter 10: Signal Processing 333
Introduction 333
Analyzing the frequency components of a signal with
a Fast Fourier Transform 337
iii
Table of Contents
Applying a linear filter to a digital signal 343
Computing the autocorrelation of a time series 349
Chapter 11: Image and Audio Processing 353
Introduction 353
Manipulating the exposure of an image 355
Applying filters on an image 358
Segmenting an image 362
Finding points of interest in an image 367
Detecting faces in an image with OpenCV 370
Applying digital filters to speech sounds 373
Creating a sound synthesizer in the notebook 377
Chapter 12: Deterministic Dynamical Systems 381
Introduction 381
Plotting the bifurcation diagram of a chaotic dynamical system 383
Simulating an elementary cellular automaton 387
Simulating an ordinary differential equation with SciPy 390
Simulating a partial differential equation – reaction-diffusion systems
and Turing patterns 394
Chapter 13: Stochastic Dynamical Systems 401
Introduction 401
Simulating a discrete-time Markov chain 402
Simulating a Poisson process 406
Simulating a Brownian motion 410
Simulating a stochastic differential equation 412
Chapter 14: Graphs, Geometry, and Geographic
Information Systems 417
Introduction 417
Manipulating and visualizing graphs with NetworkX 421
Analyzing a social network with NetworkX 425
Resolving dependencies in a directed acyclic graph with
a topological sort 430
Computing connected components in an image 434
Computing the Voronoi diagram of a set of points 438
Manipulating geospatial data with Shapely and basemap 442
Creating a route planner for a road network 446
Chapter 15: Symbolic and Numerical Mathematics 453
Introduction 453
Diving into symbolic computing with SymPy 454
Solving equations and inequalities 457

iv
Table of Contents
Analyzing real-valued functions 458
Computing exact probabilities and manipulating random variables 460
A bit of number theory with SymPy 462
Finding a Boolean propositional formula from a truth table 465
Analyzing a nonlinear differential system – Lotka-Volterra
(predator-prey) equations 467
Getting started with Sage 470
Index 473

v
Preface
We are becoming awash in the flood of digital data from scientific research, engineering,
economics, politics, journalism, business, and many other domains. As a result, analyzing,
visualizing, and harnessing data is the occupation of an increasingly large and diverse set
of people. Quantitative skills such as programming, numerical computing, mathematics,
statistics, and data mining, which form the core of data science, are more and more
appreciated in a seemingly endless plethora of fields.

My previous book, Learning IPython for Interactive Computing and Data Visualization,
Packt Publishing, published in 2013, was a beginner-level introduction to data science and
numerical computing with Python. This widely-used programming language is also one of the
most popular platforms for these disciplines.

This book continues that journey by presenting more than 100 advanced recipes for data
science and mathematical modeling. These recipes not only cover programming and
computing topics such as interactive computing, numerical computing, high-performance
computing, parallel computing, and interactive visualization, but also data analysis topics
such as statistics, data mining, machine learning, signal processing, and many others.

All of this book's code has been written in the IPython notebook. IPython is at the heart of
the Python data analysis platform. Originally created to enhance the default Python console,
IPython is now mostly known for its widely acclaimed notebook. This web-based interactive
computational environment combines code, rich text, images, mathematical equations, and
plots into a single document. It is an ideal gateway to data analysis and high-performance
numerical computing in Python.
Preface

What this book is


This cookbook contains in excess of a hundred focused recipes, answering specific questions
in numerical computing and data analysis with IPython on:

ff How to explore a public dataset with pandas, PyMC, and SciPy


ff How to create interactive plots, widgets, and Graphical User Interfaces in the
IPython notebook
ff How to create a configurable IPython extension with custom magic commands
ff How to distribute asynchronous tasks in parallel with IPython
ff How to accelerate code with OpenMP, MPI, Numba, Cython, OpenCL, CUDA, and the
Julia programming language
ff How to estimate a probability density from a dataset
ff How to get started using the R statistical programming language in the notebook
ff How to train a classifier or a regressor with scikit-learn
ff How to find interesting projections in a high-dimensional dataset
ff How to detect faces in an image
ff How to simulate a reaction-diffusion system
ff How to compute an itinerary in a road network

The choice made in this book was to introduce a wide range of different topics instead of delving
into the details of a few methods. The goal is to give you a taste of the incredibly rich capabilities
of Python for data science. All methods are applied on diverse real-world examples.

Every recipe of this book demonstrates not only how to apply a method, but also how and why
it works. It is important to understand the mathematical concepts and ideas underlying the
methods instead of merely applying them blindly.

Additionally, each recipe comes with many references for the interested reader who wants to
know more. As online references change frequently, they will be kept up to date on the book's
website (http://ipython-books.github.io).

What this book covers


This book is split into two parts:

Part 1 (chapters 1 to 6) covers advanced methods in interactive numerical computing,


high-performance computing, and data visualization.

Part 2 (chapters 7 to 15) introduces standard methods in data science and mathematical
modeling. All of these methods are applied to real-world data.

2
Preface

Part 1 – Advanced High-Performance Interactive


Computing
Chapter 1, A Tour of Interactive Computing with IPython, contains a brief but intense
introduction to data analysis and numerical computing with IPython. It not only covers
common packages such as Python, NumPy, pandas, and matplotlib, but also advanced
IPython topics such as interactive widgets in the notebook, custom magic commands,
configurable IPython extensions, and new language kernels.

Chapter 2, Best Practices in Interactive Computing, details best practices to write reproducible,
high-quality code: task automation, version control with Git, workflows with IPython, unit testing
with nose, continuous integration, debugging, and other related topics. The importance of these
subjects in computational research and data analysis cannot be overstated.

Chapter 3, Mastering the Notebook, covers advanced topics related to the IPython notebook,
notably the notebook format, notebook conversions, and CSS/JavaScript customization.
The new interactive widgets available since IPython 2.0 are also extensively covered. These
techniques make data analysis in the notebook more interactive than ever.

Chapter 4, Profiling and Optimization, covers methods to make your code faster and more
efficient: CPU and memory profiling in Python, advanced optimization techniques with NumPy
(including large array manipulations), and memory mapping of huge arrays with the HDF5 file
format and the PyTables library. These techniques are essential for big data analysis.

Chapter 5, High-performance Computing, covers advanced techniques to make your code


much faster: code acceleration with Numba and Cython, wrapping C libraries in Python with
ctypes, parallel computing with IPython, OpenMP, and MPI, and General-Purpose Computing
on Graphics Processing Units (GPGPU) with CUDA and OpenCL. The chapter ends with an
introduction to the recent Julia language, which was designed for high-performance numerical
computing and can be easily used in the IPython notebook.

Chapter 6, Advanced Visualization, introduces a few data visualization libraries that go beyond
matplotlib in terms of styling or programming interfaces. It also covers interactive visualization
in the notebook with Bokeh, mpld3, and D3.js. The chapter ends with an introduction to
Vispy, a library that leverages the power of Graphics Processing Units for high-performance
interactive visualization of big data.

Part 2 – Standard Methods in Data Science and Applied


Mathematics
Chapter 7, Statistical Data Analysis, covers methods for getting insight into data. It
introduces classic frequentist and Bayesian methods for hypothesis testing, parametric and
nonparametric estimation, and model inference. The chapter leverages Python libraries such
as pandas, SciPy, statsmodels, and PyMC. The last recipe introduces the statistical language
R, which can be easily used in the IPython notebook.

3
Preface

Chapter 8, Machine Learning, covers methods to learn and make predictions from data.
Using the scikit-learn Python package, this chapter illustrates fundamental data mining and
machine learning concepts such as supervised and unsupervised learning, classification,
regression, feature selection, feature extraction, overfitting, regularization, cross-validation,
and grid search. Algorithms addressed in this chapter include logistic regression, Naive Bayes,
K-nearest neighbors, Support Vector Machines, random forests, and others. These methods
are applied to various types of datasets: numerical data, images, and text.

Chapter 9, Numerical Optimization, is about minimizing or maximizing mathematical


functions. This topic is pervasive in data science, notably in statistics, machine learning, and
signal processing. This chapter illustrates a few root-finding, minimization, and curve fitting
routines with SciPy.

Chapter 10, Signal Processing, is about extracting relevant information from complex and
noisy data. These steps are sometimes required prior to running statistical and data mining
algorithms. This chapter introduces standard signal processing methods such as Fourier
transforms and digital filters.

Chapter 11, Image and Audio Processing, covers signal processing methods for images and
sounds. It introduces image filtering, segmentation, computer vision, and face detection with
scikit-image and OpenCV. It also presents methods for audio processing and synthesis.

Chapter 12, Deterministic Dynamical Systems, describes dynamical processes underlying


particular types of data. It illustrates simulation techniques for discrete-time dynamical
systems as well as for ordinary differential equations and partial differential equations.

Chapter 13, Stochastic Dynamical Systems, describes dynamical random processes


underlying particular types of data. It illustrates simulation techniques for discrete-time
Markov chains, point processes, and stochastic differential equations.

Chapter 14, Graphs, Geometry, and Geographic Information Systems, covers analysis and
visualization methods for graphs, social networks, road networks, maps, and geographic data.

Chapter 15, Symbolic and Numerical Mathematics, introduces SymPy, a computer algebra
system that brings symbolic computing to Python. The chapter ends with an introduction to
Sage, another Python-based system for computational mathematics.

What you need for this book


You need to know the content of this book's prequel, Learning IPython for Interactive
Computing and Data Visualization: Python programming, the IPython console and notebook,
numerical computing with NumPy, basic data analysis with pandas as well as plotting with
matplotlib. This book tackles advanced scientific programming topics that require you to be
familiar with the scientific Python ecosystem.

4
Preface

In Part 2, you need to know the basics of calculus, linear algebra, and probability theory.
These chapters introduce different topics in data science and applied mathematics (statistics,
machine learning, numerical optimization, signal processing, dynamical systems, graph theory,
and others). You will understand these recipes better if you know fundamental concepts such as
real-valued functions, integrals, matrices, vector spaces, probabilities, and so on.

Installing Python
There are many ways to install Python. We highly recommend the free Anaconda distribution
(http://store.continuum.io/cshop/anaconda/). This Python distribution contains
most of the packages that we will be using in this book. It also includes a powerful packaging
system named conda. The book's website contains all the instructions to install Anaconda
and run the code examples. You should learn how to install packages (conda install
packagename) and how to create multiple Python environments with conda.

The code of this book has been written for Python 3 (more precisely, the code has been tested
on Python 3.4.1, Anaconda 2.0.1, Windows 8.1 64-bit, although it definitely works on Linux
and Mac OS X), but it also works with Python 2.7. We mention any compatibility issue when
required. These issues are rare in this book, because NumPy does the heavy lifting in most
cases. NumPy's interface hasn't changed between Python 2 and Python 3.

If you're unsure about which Python version you should use, pick Python 3. You should only
pick Python 2 if you really need to (for example, if you absolutely need a Python package that
doesn't support Python 3, or if part of your user base is stuck with Python 2). We cover this
question in greater detail in Chapter 2, Best Practices in Interactive Computing.

With Anaconda, you can install Python 2 and Python 3 side-by-side using conda environments.
This is how you can easily run the couple of recipes in this book that require Python 2.

GitHub repositories
A home page and two GitHub repositories accompany this book:

ff The main webpage at http://ipython-books.github.io


ff The main GitHub repository, with the codes and references of all recipes, at
https://github.com/ipython-books/cookbook-code
ff Datasets used in certain recipes at https://github.com/ipython-books/
cookbook-data

The main GitHub repository is where you can:

ff Find all code examples as IPython notebooks


ff Find all up-to-date references
ff Find up-to-date installation instructions
ff Report errata, inaccuracies, or mistakes via the issue tracker

5
Other documents randomly have
different content
The Project Gutenberg eBook of For the
Defence
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: For the Defence

Author: Fergus Hume

Release date: August 23, 2017 [eBook #55420]


Most recently updated: October 23, 2024

Language: English

Credits: Produced by Charles Bowen from page scans provided by


the
Internet Archive (University of California Libraries)

*** START OF THE PROJECT GUTENBERG EBOOK FOR THE


DEFENCE ***
Transcriber's Notes:
1. Page scan source: Internet Archive
https://archive.org/details/fordefense00humeiala
(University of California Libraries)

CONTENTS

CHAPTER
I. THE MAJOR AND HIS HOUSEHOLD.
II. THE ASHANTEE DEVIL-STICK.
III. DIDO.
IV. VOODOO! VOODOO!
V. DR. ETWALD'S WARNING.
VI. A STRANGE OCCURRENCE.
VII. THE RIVALS.
VIII. A CRY IN THE NIGHT.
IX. AFTER THE DEED.
X. FURTHER MYSTERY.
XI. MAJOR JEN, DETECTIVE.
XII. THE STRANGE PERFUME.
XIII. ISABELLA.
XIV. LADY MEG.
XV. CROSS-EXAMINATION.
XVI. THE EVIDENCE OF JAGGARD.
XVII. THE STORY OF THE NIGHT.
XVIII. THE DEVIL-STICK THIEF.
XIX. FURTHER EVIDENCE.
XX. A STRANGE REQUEST.
XXI. A NINE DAY'S WONDER.
XXII. FOR THE DEFENSE,
XXIII. THE RESULT OF THE TRIAL.
XXIV. A FINAL SURPRISE.
XXV. THREE LETTERS.

FOR THE DEFENCE


BY

FERGUS HUME

AUTHOR OF
"MYSTERY OF A HANSOM CAB," "HARLEQUIN OPAL," ETC.

CHICAGO AND NEW YORK:


RAND, McNALLY & COMPANY,
PUBLISHERS.

Copyright 1897, by Fergus Hume.


Copyright, 1898, by Rand McNally & Co.

FOR THE DEFENCE.


CHAPTER I.

THE MAJOR AND HIS HOUSEHOLD.

Laurence Jen was a retired major, a bachelor, and the proprietor of a


small estate at Hurstleigh, in Surrey. On leaving the service, he
decided--not unwisely--that it was better to be a Triton in the
country than a minnow in town; and acting upon this theory he
purchased "Ashantee" from a ruined squire. Formerly the place had
been called Sarbylands, after its original owners; but Jen had
changed the name, in honor of the one campaign in which he had
participated.

He had been present at the downfall of King Koffee; he had


contracted during the expedition an ague which tormented him
greatly during his later life, and he had received a wound and a
medal. In gratitude, it is to be presumed, for these gifts of fortune,
the major, with some irony, had converted the name Sarbylands into
the barbaric appellation of a West African kingdom; and here, for
many years, he lived with his two boys.

These lads, named respectively Maurice Alymer and David Sarby,


were in no way related to the major, who, as has been stated
before, was a bachelor; but they had entered into his life in rather
an odd fashion. Alymer was the son of a beautiful girl with whom
Jen had been passionately in love, but she did not return his
affection, and married one of his brother officers, who was afterward
killed in the Ashantee war. On returning to England Jen cherished a
hope that she would reward his love by a second marriage, but the
shock of her husband's death proved too much for the fragile widow.
She died within a week after receiving the terrible news, and left
behind her a wailing infant, which was consigned to the cold charity
of indifferent relatives.

It was then that the major displayed the goodness of his heart and
the nobility of his character. Forgetting his own sorrows, he obtained
permission from the relatives to adopt the child, and to take charge
of the trifle of property coming to the lad. Then he bought
Sarbylands; set estate and house in order under the name
"Ashantee," and devoted his life to cherishing and training the lad, in
whose blue eyes he saw a look of his dead love. This Platonic
affection begotten by the deathless memory of the one passion of
his life, filled his existence completely and rendered him entirely
happy.

With regard to David Sarby, he had passed with the estate to Jen.
The boy's father, a libertine, a drunkard and a confirmed gambler,
had been forced, through his vices, to sell his ancestral home; and
within a year of the sale he had dissipated the purchase money in
debauchery. Afterward, like the sordid and pitiful coward he had
always proved himself to be, he committed suicide, leaving his only
son, whose mother had long since been worried into her grave, a
pauper and an orphan.

The collateral branches of the old Sarby family had died out; the
relatives on the mother's side refused to have anything to do with a
child who, if heredity went for anything, might prove to be a chip of
the old block; and little David might have found himself thrown on
the parish, but that Major Jen, pitying the forlorn condition of the
child, saved him from so ignominious a fate. His heart and his house
were large enough to receive another pensioner, so he took David
back to the old deserted mansion, and presented him to Maurice as
a new playfellow. Henceforth the two boys grew to manhood under
the devoted care of the cheerful old bachelor, who had protected
their helpless infancy.
The major was fairly well-to-do, having, besides his pension,
considerable private property, and he determined in the goodness of
his heart, that "the boys," as he fondly called them, should have
every advantage in starting life. He sent them both to Harrow, and
when they left that school, he called upon them to choose their
professions. Maurice, more of an athlete than a scholar, selected the
army, and the delighted major, who highly approved of his choice,
entered him at Sandhurst. Of a more reflective nature and studious
mind, David wished to become a lawyer, with a possible idea of
ending as Lord Chancellor; and accordingly his guardian sent him to
Oxford.

Both lads proved themselves worthy of Jen's goodness, and were


soon in active exercise of the professions which they had chosen.
Maurice joined a cavalry regiment and David was admitted to the
bar. Then the major was thankful. His boys were provided for, and it
only remained that each should marry some charming girl, and bring
their families to gladden an old bachelor's heart at "Ashantee." The
major had many day dreams of this sort; but alas! they were
destined never to be fulfilled. In the summer of '95 Fate began her
work of casting into dire confusion the hitherto placid lives of the
two young men.

Frequently the young barrister and the soldier came to visit their
guardian, for whom they both cherished a deep affection. On the
occasion of each visit Jen was accustomed to celebrate their
presence by a small festival, to which he would ask two or three
friends. With simple craft, the old man would invite also pretty girls,
with their mothers; in the hope that his lads might be lured into
matrimony.

The major, owing to circumstances heretofore related, was a


confirmed bachelor, but he did not intend that his boys should follow
so bad an example. He wished Maurice to marry Miss Isabella Dallas,
a charming blonde from the West Indies; and David he designed as
the husband of Lady Meg Brance, daughter of Lord Seamere. But
Jen was mistaken in thinking that he could guide the erratic
affections of youth, as will hereafter be proved. Sure enough, the
lads fell in love, but both with the same woman, a state of things not
anticipated by the major, who was too simple to be a matchmaker.

On this special occasion, however, no ladies were present at the little


dinner, and besides Jen and his two boys. Dr. Etwald was the only
guest. About this man with the strange name there is something to
be said.

He was tall, he was thin, with a dark, lean face, and fiery watchful
dark eyes. For three years he had been wasting his talents in the
neighboring town of Deanminster; when, if intellect were in
question, he should have been shouldering his way above the crowd
of mediocrities in London. The man was dispassionate, brilliant and
persevering; he had in him the makings not only of a great
physician, but of a great man; and he was wasting his gifts in a dull
provincial town. He was unpopular in Deanminster, owing to the
absence of what is termed "a good bedside manner," and the
invalids of the cathedral city and Hurstleigh, for he had patients in
both places, resented his brusque ways and avoidance of their
scandal-mongering tea parties. Also he was a mystery; than which
there can be no greater sin in provincial eyes. No one knew who
Etwald was, or whence he came, or why he wasted his talents in the
desert of Deanminster; and such secret past which he declined to
yield up to the most persistent questioner, accentuated the distrust
caused by his sombre looks and curt speeches. Provincial society is
intolerant of originality.

Etwald had become acquainted with Jen professionally, and having


cured the major of one of his frequent attacks of ague, he had
passed from being a mere medical attendant into the closer
relationship of a friend. The boys had met him once or twice, but
neither of them cared much for his sombre personality, and they
were not overpleased to find that the major had invited the man to
meet them on the occasion of this special dinner.
But Jen, good, simple soul, was rather taken with Etwald's
mysticism, and, moreover, pitied his loneliness. Therefore he
welcomed this intellectual pariah to his house and board; and on this
fine June evening Etwald was enjoying an excellent dinner in the
company of three cheerful companions.

Outside, the peaceful landscape was filled with a warm amber light,
and this poured into the oak-paneled dining-room through three
French windows which opened onto a close-shaven lawn. Dinner
was at an end; Jaggard, the major's valet, butler and general
factotum, had placed the wines before his master, and was now
handing around cigars and cigarettes. All being concluded to his
satisfaction--no easy attainment, for Jaggard, trained in military
fashion, was very precise--he departed, closing the door after him.
The warm light of the evening flashed on the polished table--Major
Jen was sufficiently old-fashioned to have the cloth removed for
desert--and lighted up the four faces around it with pale splendor.
This quartette of countenances is not unworthy of a detailed
description.

Major Jen's calls for least. His face was round and red, with a terrific
blonde mustache fiercely curled. He had merry blue eyes, sparse
hair, more than touched with gray, and an expression of good-humor
which was the index to his character. Man, woman and child trusted
Jen on the spot, nor was it ever said that such trust was misplaced.
Even the most censorious could find no fault with the frank and
kindly major, and he had more friends and more pensioners and
fewer enemies than any man in the shire. Can any further
explanation be required of so simple and easily understood a
character?

Lieutenant Maurice Alymer was also blonde, and also had blue eyes
and a jaunty mustache, somewhat smaller than his senior's. His hair
was yellow and curly, his features were boldly cut, and his six foot of
flesh and muscle was straight and lithe. Athlete was stamped
strongly on his appearance, and if not clever, he was at least
sufficiently good-looking and good-natured to make him almost as
popular as the major. Jen always maintained that Maurice was the
living image of himself when a dashing young officer, out in
Ashantee; but as the good major was considerably under the middle
height and Maurice considerably over it, this statement must be
accepted with some reserve. It passed as one of Jen's jokes, for a
mild quality of which he was noted.

The other two men had dark and strong faces, which differed
entirely from the Saxon simplicity and good looks of the major and
Maurice. David was clean-shaven and almost as swart as Etwald,
and his expression was that of a being with powerful passions, held
in check by sheer force of will. He was broad and strongly built; and
his smooth black hair, parted in the middle, was brushed carefully
from a bold and rather protuberant forehead. The young barrister
was somewhat of a dandy, but no one who once looked at his face
thought of his dress affectations or dapper appearance. They saw
intellect, pride and resolute will stamped upon the pale countenance.
Men with such faces end usually in greatness; and it seemed unlikely
that David Sarby, barrister and ambitious youth, would prove an
exception to the rule.

Lastly Etwald. It is difficult to describe the indescribable. He was


austere in face, like Dante, with hollow cheeks, and a pallid hue
which told of midnight studies. If he had passions, they could not be
discerned in his features. Eye and mouth and general expression
were like a mask. What actually lay behind that mask no one ever
knew, for it was never off. His slightly hollow chest, his lean and
nervous hands, and a shock of rather long, curling hair, tossed from
a high forehead, gave Etwald the air of a student. But there was
something sinister and menacing in his regard. He looked dangerous
and more than a trifle uncanny. Physically, mentally, morally he was
an enigma to the bovine inhabitants of Deanminster and Hurstleigh.

Major Jen sustained the burden of conversation, for Maurice was


absent-minded, and David, physiognomically inclined, was silently
attempting to read the inscrutable countenance of Etwald. As for this
latter, he sat smoking, with his brilliant eyes steadily fixed upon
Maurice. The young man felt uneasy under the mesmeric gaze of the
doctor, and kept twisting and turning in his seat. Finally he broke out
impatiently in the midst of the major's babble, and asked Etwald a
direct question.

"Does my face remind you of anyone?" he demanded rather sharply.

"Yes, Mr. Alymer," replied Etwald, deliberately, "it reminds me of a


man who died."

"Dear me!" said Jen, with a sympathetic look.

"Was he a friend of yours, doctor?"

"Well, no, major, I can't say that he was. In fact," added Etwald,
with the air of a man making a simple statement, "I hated him!"

"I hope you don't hate me?" said Maurice, rather annoyed.

"No, Mr. Alymer, I don't hate you," replied the doctor, in a colorless
tone. "Do you believe in palmistry?" he asked, suddenly.

"No!" said Maurice, promptly,

"All rubbish!" added the major, selecting a fresh cigar.

"What do you say, Mr. Sarby?" asked Etwald, turning to the lawyer.

"I am a skeptic, also," said David, with a laugh. "And you?"

"I am a believer."

Here Etwald rose and crossed over to where Maurice was sitting.
The young man, guessing his errand, held out his left hand with a
smile. Etwald scrutinized it closely, and returned to his seat.
"Life in death!" he said calmly. "Read that riddle, Mr. Alymer. Life in
death."

CHAPTER II.

THE ASHANTEE DEVIL-STICK.

"Life in death!" repeated Maurice, in puzzled tones. "And what do


you mean by that mystical jargon, doctor?"

"Ah, my friend, there comes in the riddle."

"Paralysis?" suggested David, in a jesting manner, but with some


seriousness.

"No; that is not the answer."

"Catalepsy?" guessed Major Jen, giving his mustache a nervous


twist.

"Nor that, either."

Maurice, whose nerves were proof against such fantasies, laughed


disbelievingly.

"I don't believe you know the answer to your own riddle," he said
calmly.

Etwald shrugged his shoulders.


"I don't know for certain, Mr. Alymer, but I can guess."

"Tell us your guess, doctor; as it interests me so nearly, I have a


right to know."

"Bad news comes quickly enough in the telling," said the doctor,
judicially, "so I shall say nothing more. Life in death is your fate, Mr.
Alymer; unless," he added, with a swift and penetrating glance, "you
choose to avert the calamity."

"Can I do so?"

"Yes, and in an easy manner. Never get married."

Maurice flushed crimson, and, resenting the mocking tone of Etwald,


half rose from his seat; but without moving a finger, Etwald
continued in a cold tone:

"You are in love with a young lady, and you wish to marry her!"

"Quite right, quite right!" broke in Major Jen, heartily. "I want
Maurice to marry."

"Then you want him to meet his fate of life in death!" said Etwald,
curtly.

The others stared at him, and with the skepticism of thoroughly


healthy minds refused to attach much importance to Etwald's
mysticism. Jen was the first to speak, and he did so in rather a stiff
way, quite different from his usual jovial style of conversation.

"My dear Etwald, if I did not know you so well, I should take you for
a charlatan."

"I am no charlatan, major," rejoined Etwald, coolly. "I ask no money


for my performance."

"So it is a performance, after all?" said David, carelessly.


"If you choose to call it so. Only I repeat my warning to Mr. Alymer.
Never get married."

Maurice laughed.

"I am afraid it is too late for me to take your advice, doctor," he said,
merrily. "I am in love."

"I know you are, and I admire your taste."

"Pardon me, doctor," said Maurice, stiffly. "I mention no names."

"Neither do I, but I think of one name, my friend."

Here David, who had been fidgeting with his cigar, broke in
impatiently.

"Now you are making a mystery out of a plain, common-sense


question," he said, irritably. "We all know that Maurice is in love,"
here he raised his eyes suddenly, and looked keenly at his friend,
"with Lady Meg Brance."

Major Jen chuckled and rubbed his hands together in a satisfied


manner. Etwald bent his sombre looks on Maurice, and that young
man, biting his lip, took up the implied challenge in Sarby's remark,
and answered plainly:

"I am not in love with Lady Meg, my dear fellow," said he, sharply;
"but if you must know, I admire"--this with emphasis--"Miss Dallas."

The brow of Sarby grew black, and in his turn he rose to his feet.

"I am glad to hear it is only 'admire,'" he remarked, slowly, "for had


the word been any other I should have resented it."

"You! And upon what grounds?" cried Alymer, flushing out in a rage.

"That is my business."
"And mine, too," said Maurice, hotly. "Isabella is--"

"I forbid you to call Miss Dallas by that name," declared David, in an
overbearing manner.

"You--you--you forbid me!"

"Come, come, boys!" said Jen, annoyed at this scene between two
hot-headed young men, who were not yet gifted with the self-
restraint of experience.

"Don't talk like this. You are at my table. There is a stranger" (here
he bowed ceremoniously to Etwald) "or shall I say a friend, present!"

"Say a friend," observed Etwald, calmly, "although I am about to say


that which may cause these two young gentlemen to look upon me
as an enemy."

"What do you mean?" asked Maurice, turning his still frowning face
toward this strange and enigmatic man.

"What I say, Mr. Alymer! You--admire Miss Dallas?"

"Why bring her name into the question? Yes, I admire Miss Dallas."

"And you, Mr. Sarby, I can tell from your attitude, from your look;
you love Miss Dallas."

David was taken aback by this strange speaking.

"Yes. I--I--I do love Miss Dallas."

"I guessed as much," resumed Etwald, with a cold smile. "Now, it is


strange--"

"It is strange that a lady's name should be thus introduced," said


Jen, annoyed at the tone of the conversation. "Let us drop the
subject. Another cigar, Maurice. David, the wine is with you. Dr.
Etwald--"

"One moment, major. I wish we three to understand one another"--


here the doctor hesitated, then went on in an impressive voice--
"about Miss Dallas!"

"Why do you speak of her?" asked Maurice, fiercely, while David


looked loweringly at Etwald.

"Because I love her!"

"You love her!"

The two young men burst out simultaneously with the speech in
tones of sheer astonishment, and stared at Etwald as at some
strangle animal. That this elderly man--Etwald was midway between
thirty and forty, but that looked elderly to these boys of twenty-five--
should dare to love Isabella Dallas, was a thing unheard of. She so
young, so beautiful, so full of divine youth and diviner womanhood;
he so sombre, pale and worn with intellectual vigils; with a
mysterious past, a doubtful present and a problematic future.

Maurice and David, divided one against the other by their passion for
the same woman, united in a feeling of rage and contempt against
this interloper, who dared to make a third in their worship of
Isabella. They looked at Etwald, they looked at one another, and
finally both began to laugh. Jen frowned at the sound of their mirth,
but Etwald, in nowise discomposed, sat unsmiling in his seat waiting
for further developments.

"Oh, it is too absurd!" said Maurice, resuming his seat.

"Why?"

Etwald put the question with the greatest calmness, stared steadily
at the young man, and waited for the reply, which he knew would be
difficult to make.

"Oh, because--because--"

"Never mind explaining, Mr. Alymer. I can guess your objection. I am


too old, too plain, too poor for this charming young lady. You, on the
contrary, are young, passing well off, and handsome--all the gifts of
fortune are on your side. Decidedly," added the doctor, "you hold the
best hand. Well, we shall see who will win this game--as we may call
it."

"And what about me?" said David. "You forget that I am a third
player. Come, Etwald, you have prophesied about Maurice; now read
my fate."

"No," said Etwald, rising. "We have talked long enough on this
subject. It is plain that we three men are in love with the same
woman. You can't blame me, nor I you. Miss Dallas is a sufficiently
beautiful excuse for our madness. I spoke out simply because I want
you both to understand the position. You are warned, and we can
now do battle for the smiles of this charming lady. Let the best man
win!"

"Nothing could be fairer than that," said Jen, quickly; "but I agree
with you, doctor, that the subject has been sufficiently discussed;
but, indeed, if you will pardon me saying so, it should have never
been begun. Let us go to the smoking-room."

Thither the three young men went in the wake of the major. It was a
comfortable room, with one wide window, which at the present
moment was open. Outside, the light of the newly-risen moon
bathed lawn and trees and flowers in a flood of cold silver; and the
warm radiance of the lamp poured out rays of gold into the
wonderful white world without. The three men sat down in
comfortable chairs, and the major went to get out a particular brand
of cigars which he offered to favored guests.
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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like