100% found this document useful (5 votes)
83 views

Download Introduction to Python in Earth Science Data Analysis 1st Edition Maurizio Petrelli ebook All Chapters PDF

Petrelli

Uploaded by

marathokala90
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 (5 votes)
83 views

Download Introduction to Python in Earth Science Data Analysis 1st Edition Maurizio Petrelli ebook All Chapters PDF

Petrelli

Uploaded by

marathokala90
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/ 55

Download Full Version ebook - Visit ebookmeta.

com

Introduction to Python in Earth Science Data


Analysis 1st Edition Maurizio Petrelli

https://ebookmeta.com/product/introduction-to-python-in-
earth-science-data-analysis-1st-edition-maurizio-petrelli/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmeta.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

Introduction to Python for Econometrics, Statistics and


Data Analysis. 5th Edition Kevin Sheppard.

https://ebookmeta.com/product/introduction-to-python-for-econometrics-
statistics-and-data-analysis-5th-edition-kevin-sheppard/

ebookmeta.com

Python Data Analytics Data Analysis and Science Using


Pandas Matplotlib and the Python Programming Language 1st
Edition Nelli Fabio
https://ebookmeta.com/product/python-data-analytics-data-analysis-and-
science-using-pandas-matplotlib-and-the-python-programming-
language-1st-edition-nelli-fabio/
ebookmeta.com

Python Data Analytics Data Analysis and Science Using


Pandas Matplotlib and the Python Programming Language 1st
Edition Nelli Fabio
https://ebookmeta.com/product/python-data-analytics-data-analysis-and-
science-using-pandas-matplotlib-and-the-python-programming-
language-1st-edition-nelli-fabio-2/
ebookmeta.com

Woven Threads Threads of Time Book 3 1st Edition Stevie


Macfarlane

https://ebookmeta.com/product/woven-threads-threads-of-time-
book-3-1st-edition-stevie-macfarlane/

ebookmeta.com
Hidden Out in the Open Spanish Migration to the United
States 1875 1930 1st Edition Phylis Cancilla Martinelli
Editor Ana Varela Lago Editor
https://ebookmeta.com/product/hidden-out-in-the-open-spanish-
migration-to-the-united-states-1875-1930-1st-edition-phylis-cancilla-
martinelli-editor-ana-varela-lago-editor/
ebookmeta.com

Overcoming Challenges in Online Learning: Perspectives


from Asia and Africa 1st Edition Areej Elsayary

https://ebookmeta.com/product/overcoming-challenges-in-online-
learning-perspectives-from-asia-and-africa-1st-edition-areej-elsayary/

ebookmeta.com

Seeing People Through Unleash Your Leadership Potential


with the Process Communication Model 1st Edition Nate
Regier
https://ebookmeta.com/product/seeing-people-through-unleash-your-
leadership-potential-with-the-process-communication-model-1st-edition-
nate-regier/
ebookmeta.com

Socializing Minds: Intersubjectivity in Early Modern


Philosophy 1st Edition Martin Lenz

https://ebookmeta.com/product/socializing-minds-intersubjectivity-in-
early-modern-philosophy-1st-edition-martin-lenz/

ebookmeta.com

A Tale of Two Dukes Seven Omegas for Seven Alphas Book 2


1st Edition Vivian Murdoch

https://ebookmeta.com/product/a-tale-of-two-dukes-seven-omegas-for-
seven-alphas-book-2-1st-edition-vivian-murdoch/

ebookmeta.com
Gorillas Can Dance Lessons from Microsoft and Other
Corporations on Partnering with Startups 1st Edition
Shameen Prashantham
https://ebookmeta.com/product/gorillas-can-dance-lessons-from-
microsoft-and-other-corporations-on-partnering-with-startups-1st-
edition-shameen-prashantham/
ebookmeta.com
Maurizio Petrelli

Introduction
to Python
in Earth Science
Data Analysis
From Descriptive Statistics
to Machine Learning
Springer Textbooks in Earth Sciences,
Geography and Environment
The Springer Textbooks series publishes a broad portfolio of textbooks on Earth
Sciences, Geography and Environmental Science. Springer textbooks provide
comprehensive introductions as well as in-depth knowledge for advanced studies.
A clear, reader-friendly layout and features such as end-of-chapter summaries, work
examples, exercises, and glossaries help the reader to access the subject. Springer
textbooks are essential for students, researchers and applied scientists.

More information about this series at http://www.springer.com/series/15201


Maurizio Petrelli

Introduction to Python
in Earth Science Data
Analysis
From Descriptive Statistics to Machine
Learning
Maurizio Petrelli
Department of Physics and Geology
University of Perugia
Perugia, Italy

ISSN 2510-1307 ISSN 2510-1315 (electronic)


Springer Textbooks in Earth Sciences, Geography and Environment
ISBN 978-3-030-78054-8 ISBN 978-3-030-78055-5 (eBook)
https://doi.org/10.1007/978-3-030-78055-5

© The Editor(s) (if applicable) and The Author(s), under exclusive license to Springer Nature
Switzerland AG 2021
This work is subject to copyright. All rights are solely and exclusively licensed by the Publisher, whether
the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse
of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and
transmission or information storage and retrieval, electronic adaptation, computer software, or by similar
or dissimilar methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication
does not imply, even in the absence of a specific statement, that such names are exempt from the relevant
protective laws and regulations and therefore free for general use.
The publisher, the authors and the editors are safe to assume that the advice and information in this book
are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or
the editors give a warranty, expressed or implied, with respect to the material contained herein or for any
errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
To my daughters Agata, Anna, and Caterina,
my wife Arianna, and Atomo who completes
the family
Preface

The idea of writing this book came to me in 2015 when I started teaching a course
entitled “Data Analysis and Interpretation in Earth Science” at the Department of
Physics and Geology of Perugia University. From the beginning of the course, I
realized that many of my students were strongly interested in data managing, visu-
alizing, and modeling in Python. I also realized that no reference book was avail-
able for teaching Python to geologists. Although numerous books present Python
to programmers at all levels, from beginners to experts, they mostly focus solely on
programming techniques, without discussing real applications, especially in geology.
In other words, a book devoted to Earth Scientists was missing. The project grew
and became structured while teaching the basics of Python to Earth Scientists at
the Eötvös University Budapest (Hungary) and at Leibniz Universität of Hannover
(Germany) in December 2018 and February 2020, respectively. Sadly, by the begin-
ning of March 2020, the COVID-19 pandemic had dramatically spread to all regions
of Italy and, on March 4th, the Italian government shut down all schools and univer-
sities nationwide, forcing me to stay at home like most Italians. In one of the most
confusing and insecure moments of my life, I decided to start writing this book.
“Introduction to Python in Earth Science Data Analysis” is devoted to Earth Scien-
tists, at any level, from students to academics and professionals, who would like to
harness the power of Python to visualize, analyze, and model geological data. No
experience in programming is required to use this book. If you are working in the
Earth Sciences, are a novice programmer, and would like to exploit the power of
Python in your projects, this is the right place for you.

Assisi, Italy Maurizio Petrelli


March 2021

vii
Acknowledgments

I would like to acknowledge all the people who encouraged me when I started
planning this project and all those who supported me during the writing. The first
one is Diego Perugini, who allowed me to re-enter academia in 2014 through the
Chronos project after a hiatus of three years. I also thank the Erasmus Plus (E+)
program that supported my foreign teaching excursions in Hungary and Germany,
including Roberto Rettori and Sabrina Nazzareni, who oversaw the E+ program for
my department, and the local E+ officers at the University of Perugia (Sonia Trinari
and Francesca Buco) and at the Tiber Umbria Comett Education Programme (Maria
Grazia Valocchia). Professor Francois Holtz (Leibniz Universität Hannover) and
Professor Szabolcs Harangi (Eötvös University Budapest) are also kindly acknowl-
edged for allowing me to run the “Python in Earth Sciences” courses at their insti-
tutions. The Department of Physics and Geology at University of Perugia, who
supported this book through the Engage FRB2019 project, also has my gratitude. I
also give my heartfelt thanks to my family, who put up with me as I wrote this book.
Finally, I sincerely thank Aviva Loew (Academic Language Experts), Giuseppe la
Spina, Eleonora Carocci, and Diego González-García for their critical suggestions,
which have largely improved this book.
Just before I starting writing these acknowledgments, I received a message on
my smartphone stating that I had an appointment for a COVID-19 vaccination the
following day (March 3, 2021), exactly a year to the day after the initial lockdown in
Italy. I interpreted this notification as a message of belief. I hope that the worldwide
vaccination campaigns that have been launched will signal the beginning of a new era
of beloved “normality” in our lives and that the time for resilience against COVID-19
is coming to an end. Now should be a time of empathy, cooperation, and rebirth.

ix
Overview

Let me Introduce Myself

Hi and welcome. My name is Maurizio Petrelli and I currently work at the Depart-
ment of Physics and Geology, University of Perugia (UniPg). My research focuses
on the petrological characterization of volcanoes with an emphasis on the dynamics
and timescales of pre-eruptive events. For this work, I combine classical and uncon-
ventional techniques. Since 2002, I’ve worked intensely in the laboratory, mainly
focusing on the development UniPg’s facility for Laser Ablation Inductively Coupled
Plasma Mass Spectrometry (LA-ICP-MS). In February 2006, I obtained my Ph.D.
degree with a thesis entitled “Nonlinear Dynamics in Magma Interaction Processes
and their Implications on Magma Hybridization.” Currently, I am developing a new
line of research at UniPg, Department of Physics and Geology, for applying Machine
Learning techniques in Geology. Finally, I also manage the LA-ICP-MS laboratory
at UniPg.

Organization of Book

The book is organized into five parts plus three appendixes. The Part I, entitled
“Python for Geologists: A Kickoff,” focuses on the very basics of Python program-
ming, from setting up an environment for scientific computing to solving your first
geology problems using Python. The Part II is entitled “Describing Geological Data”
and explains how to start visualizing (i.e., making plots) and generating descriptive
statistics, both univariate and bivariate. The Part III, entitled “Integrals and Differ-
ential Equations in Geology,” discusses integrals and differential equations while
highlighting various applications in geology. The Part IV deals with “Probability
Density Functions and Error Analysis” applied to the evaluation and modeling of
Earth Science data. Finally, the Part V, entitled “Robust Statistics and Machine Learn-
ing” analyzes data sets that depart from normality (statistically speaking) and the
application of machine learning techniques to data modeling in the Earth Sciences.

xi
xii Overview

Styling Conventions

I use conventions throughout this book to identify different types of information. For
example, Python statements, commands, and variables used within the main body of
the text are set in italics.
Consider the following quoted text as an example “There are many options to
create multiple subplots in matplotlib. In my opinion, the easiest approach is to
create an empty figure [i.e., fig = plt.figure(), then add multiple axes (i.e., subplots)
by using the method fig.add_subplot(nrows, ncols, index)]. The parameters nrows,
ncols, and index indicate the numbers of rows and columns (ncols) and the positional
index. In detail, index starts at 1 in the upper-left corner and increases to the right.
To better understand, consider the code listing 4.4.”
A block of Python code is highlighted as follows:

Listing 1 Example of code listing in Python

Shared Codes

All code presented in this book is tested on the Anaconda Individual Edition ver.
2021.5 (Python 3.8.8) and is available at my GitHub repository ( Petrelli-m):
http://bit.ly/python_earth_science

Involvement and Collaborations

I am always open to new collaborations worldwide. Feel free to contact me by mail


to discuss new ideas or propose a collaboration. You can also reach me through
my personal website or by Twitter. I love sharing the content of this book in short
courses everywhere. If you are interested, please contact me to organize a visit to
your institution.
Personal contacts:
maurizio.petrelli@unipg.it
@mauripetre
https://www.mauriziopetrelli.info
Contents

Part I Python for Geologists: A Kickoff


1 Setting Up Your Python Environment, Easily . . . . . . . . . . . . . . . . . . . . 3
1.1 The Python Programming Language . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Programming Paradigms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 A Local Python Environment for Scientific Computing . . . . . . . . 5
1.4 Remote Python Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.5 Python Packages for Scientific Applications . . . . . . . . . . . . . . . . . . 8
1.6 Python Packages Specifically Developed for Geologists . . . . . . . . 9
2 Python Essentials for a Geologist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.1 Start Working with IPython Console . . . . . . . . . . . . . . . . . . . . . . . . 11
2.2 Naming and Style Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.3 Working with Python Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.4 Conditional Statements, Indentation, Loops, and Functions . . . . . 17
2.5 Importing External Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.6 Basic Operations and Mathematical Functions . . . . . . . . . . . . . . . . 21
3 Solving Geology Problems Using Python: An Introduction . . . . . . . . 25
3.1 My First Binary Diagram Using Python . . . . . . . . . . . . . . . . . . . . . 25
3.2 Making Our First Models in Earth Science . . . . . . . . . . . . . . . . . . . 32
3.3 Quick Intro to Spatial Data Representation . . . . . . . . . . . . . . . . . . . 36

Part II Describing Geological Data


4 Graphical Visualization of a Geological Data Set . . . . . . . . . . . . . . . . . 43
4.1 Statistical Description of a Data Set: Key Concepts . . . . . . . . . . . . 43
4.2 Visualizing Univariate Sample Distributions . . . . . . . . . . . . . . . . . . 44
4.3 Preparing Publication-Ready Binary Diagrams . . . . . . . . . . . . . . . 47
4.4 Visualization of Multivariate Data: A First Attempt . . . . . . . . . . . 66
5 Descriptive Statistics 1: Univariate Analysis . . . . . . . . . . . . . . . . . . . . . 67
5.1 Basics of Descriptive Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
5.2 Location . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

xiii
xiv Contents

5.3 Dispersion or Scale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72


5.4 Skewness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
5.5 Descriptive Statistics in Pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.6 Box Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
6 Descriptive Statistics 2: Bivariate Analysis . . . . . . . . . . . . . . . . . . . . . . . 83
6.1 Covariance and Correlation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
6.2 Simple Linear Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
6.3 Polynomial Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.4 Nonlinear Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

Part III Integrals and Differential Equations in Geology


7 Numerical Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
7.1 Definite Integrals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
7.2 Basic Properties of Integrals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
7.3 Analytical and Numerical Solutions of Definite Integrals . . . . . . . 101
7.4 Fundamental Theorem of Calculus and Analytical Solutions . . . . 101
7.5 Numerical Solutions of Definite Integrals . . . . . . . . . . . . . . . . . . . . 103
7.6 Computing the Volume of Geological Structures . . . . . . . . . . . . . . 109
7.7 Computing the Lithostatic Pressure . . . . . . . . . . . . . . . . . . . . . . . . . 110
8 Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
8.2 Ordinary Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
8.3 Numerical Solutions of First-Order Ordinary Differential
Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
8.4 Fick’s Law of Diffusion—A Widely Used Partial
Differential Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

Part IV Probability Density Functions and Error Analysis


9 Probability Density Functions and Their Use in Geology . . . . . . . . . . 137
9.1 Probability Distribution and Density Functions . . . . . . . . . . . . . . . 137
9.2 The Normal Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.3 The Log-Normal Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
9.4 Other Useful PDFs for Geological Applications . . . . . . . . . . . . . . . 144
9.5 Density Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
9.6 The Central Limit Theorem and Normal Distributed Means . . . . 152
10 Error Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
10.1 Dealing with Errors in Geological Measurements . . . . . . . . . . . . . 155
10.2 Reporting Uncertainties in Binary Diagrams . . . . . . . . . . . . . . . . . 162
10.3 Linearized Approach to Error Propagation . . . . . . . . . . . . . . . . . . . 168
10.4 The Mote Carlo Approach to Error Propagation . . . . . . . . . . . . . . . 172
Contents xv

Part V Robust Statistics and Machine Learning


11 Introduction to Robust Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
11.1 Classical and Robust Approaches to Statistics . . . . . . . . . . . . . . . . 181
11.2 Normality Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
11.3 Robust Estimators for Location and Scale . . . . . . . . . . . . . . . . . . . . 186
11.4 Robust Statistics in Geochemistry . . . . . . . . . . . . . . . . . . . . . . . . . . 192
12 Machine Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
12.1 Introduction to Machine Learning in Geology . . . . . . . . . . . . . . . . 195
12.2 Machine Learning in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
12.3 A Case Study of Machine Learning in Geology . . . . . . . . . . . . . . . 197

Appendix A: Python Packages and Resources for Geologists . . . . . . . . . . . 209


Appendix B: Introduction to Object Oriented Programming . . . . . . . . . . 211
Appendix C: The Matplotlib Object Oriented API . . . . . . . . . . . . . . . . . . . . 215
Appendix D: Working with Pandas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Further Readings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Part I
Python for Geologists: A Kickoff
Chapter 1
Setting Up Your Python Environment,
Easily

1.1 The Python Programming Language

Python is a high-level, modular, interpreted programming language.1 What does this


mean? A high-level programming language is characterized by a strong abstraction
that cloaks the details of the computer so that the code is easy to understand for
humans. Python is modular, which means that it supports modules and packages that
allow program flexibility and code reuse. In detail, Python is composed of a “core”
that deals with all basic operations plus a wide ecosystem of specialized packages
to perform specific tasks. To be clear, a Python package or library is a reusable
portion of code, which is a collection of functions and modules (i.e., a group of
functions) allowing the user to complete specialized tasks such as reading an excel
file or drawing a publication-ready diagram.
Python is an interpreted language (like MATLAB, Mathematica, Maple, and R).
Conversely, C or FORTRAN are compiled languages. What is the difference between
compiled and interpreted languages? Roughly speaking, with compiled languages, a
translator compiles each code listing in an executable file. Once compiled, any target
machine can directly run the executable file. Interpreted languages compile code in
real time during each execution. The main difference for a novice programmer is that
interpreted code typically runs slower than compiled executable code. However, per-
formance is not an issue in most everyday operations. Performance starts becoming
significant in computing-intensive tasks such as complex fluid dynamic simulations
or three-dimensional (3D) graphical applications. If needed, the performance of
Python can be significantly improved with the support of specific packages such as
Numba, which can compile Python code. In this case, Python code approaches the
speed of C and FORTRAN.
Being an interpreted language, Python facilitates code exchange over different
platforms (i.e., cross-platform code exchange), fast prototyping, and great flexibility.

1 https://www.python.org.
© The Author(s), under exclusive license to Springer Nature Switzerland AG 2021 3
M. Petrelli, Introduction to Python in Earth Science Data Analysis,
Springer Textbooks in Earth Sciences, Geography and Environment,
https://doi.org/10.1007/978-3-030-78055-5_1
4 1 Setting Up Your Python Environment, Easily

Some convincing arguments for Earth scientists to start learning Python are that
(1) its syntax is easy to learn; (2) it is highly flexible; (3) it enjoys the support of a
large community of users and developers; (4) it is free and open-source; and (5) it
will improve your skills and proficiency.

1.2 Programming Paradigms

A programming paradigm is a style or general approach to writing code [7, 18,


19]. As a zeroth-order approximation, two archetypal paradigms dominate program-
ming: imperative and declarative. Imperative programming mainly focuses on “how”
to solve a problem, whereas declarative programming focuses on “what” to solve.
Starting from these two archetypes, programmers have developed many derived
paradigms, such as procedural, object-oriented, functional, logic, or aspect-oriented,
just to to cite a few. The selection of a specific programming paradigm to develop
your code depends on the overall nature of your project and final scope of your
work. For parallel computing, the functional approach provides a well-established
framework. However, given that an exhaustive documentation about programming
paradigms is beyond the scope of this book, I will only illustrate those paradigms
that are supported in Python.
The Python programming language is primarily designed for object-oriented pro-
gramming, although it also supports, sometime spuriously, purely imperative, pro-
cedural, and functional paradigms [7, 18, 19]:
Imperative. The imperative approach is the oldest and simplest programming
paradigm; one simply provides a defined sequence of instructions to a computer.
Procedural. The procedural approach is a subset of imperative programming.
Instead of simply providing a sequence of instructions, it stores portions of code in
one or more procedures (i.e., subroutines or functions). Any given procedure can be
called at any point during the program execution, allowing for code organization and
reuse.
Object-oriented. Like the procedural style, the object-oriented approach is a
subset (i.e., an evolution) of imperative programming. Objects are the key elements
in object-oriented programming. One of the main benefits of this approach is that it
maintains a strong relation with real-world entities (e.g., shopping carts in websites,
WYSIWYG environments).
Functional. The functional approach is a declarative type of programming. The
purely functional paradigm bases the computation on evaluating mathematical func-
tions and is well suited for high-load, parallel computing applications.
In this introductory book we will take advantage of Python’s flexibility without
focusing too much on specific code styling or on a particular paradigm. Specifically,
our code remains mainly imperative for the easiest tasks but becomes more procedural
for more advanced modeling. Also, we benefit from the many object-oriented libraries
(e.g., pandas and matplotlib) developed for Python.
1.3 A Local Python Environment for Scientific Computing 5

1.3 A Local Python Environment for Scientific Computing

Two main strategies are available to create a Python environment suitable for scien-
tific computing on your personal computer: (1) install the Python core and add all
required scientific packages separately; or (2) install a “ready-to-use” Python envi-
ronment, specifically developed for scientific purposes. You can try both options but
I suggest starting with option (2) because it requires almost zero programming skills
and you will be ready to immediately and painlessly start your journey in the world
of Python.
An example of a “ready-to-use” scientific Python environment is the Anaconda
Python Distribution.2 Anaconda Inc. (previously Continuum Analytics) develops
and maintains the Anaconda Python distribution, providing different solutions that
include a free release and two pay versions. The Individual Edition is the free option
(and our choice); it is easy to install and offers community-driven support. To install
the Individual Edition of the Anaconda Python distribution, I suggest following
the directives given in the official documentation.3 First, download and run the
most recent stable installer for your Operating System (i.e., Windows OS, Mac OS
or Linux). For Windows and Mac OS, a graphical installer is available. The instal-
lation procedure is the same as for any other software application. The Anaconda
installer automatically installs the Python core and Anaconda Navigator, plus about
250 packages defining a complete environment for scientific visualization, analysis,
and modeling. Over 7500 additional packages can be installed individually, as the
need arises, from the Anaconda repository with the “conda”4 package management
system.
The Anaconda Navigator is a desktop graphical user interface (GUI), which means
that it is a program that allows you to launch applications, install packages, and
manage environments without using command-line instructions (Fig. 1.1).
From the Anaconda Navigator, we can launch two of the main applications that
we will use to write code, run the modeling, and visualize the results. They are the
Spyder application and the JupyterLab.
Spyder5 is an Integrated Development Environment (IDE), i.e., a software appli-
cation, providing a set of comprehensive facilities for software development and
scientific programming. It combines a text editor to write code, inspection tools for
debugging, and an interactive Python console for code execution. We will spend most
of our time using Spyder. Figure 1.2 shows a screenshot of the Spider IDE.
JupyterLab is a web-based development environment to manage Jupyter Note-
books, which are web applications that allow you to create and share documents
containing live code, equations, visualizations, and narrative text. Figure 1.3 shows
a screenshot of a Jupyter Notebook.

2 https://www.anaconda.com.
3 https://www.anaconda.com/products/individual/.
4 https://docs.conda.io/.
5 https://www.spyder-ide.org.
6 1 Setting Up Your Python Environment, Easily

Fig. 1.1 Screenshot of the Anaconda Navigator

Variable Explorer

Text editor Interactive console

Fig. 1.2 Screenshot of Spider IDE. The text editor for writing code is on the left. The bottom-right
panel is the IPython interactive console, and the top-right panel is the Variable Explorer
1.3 A Local Python Environment for Scientific Computing 7

Fig. 1.3 Screenshot of Jupyter Notebook combining narrative text, code, and visualizations

Both Sypder and JupyterLab allow you to write code, perform computations, and
report the results. There is not a preferred choice. My personal choice is to use Spyder
and Jupyter Lab for research and teaching, respectively.

1.4 Remote Python Environments

Remote Python environments are those running in a computer system or virtual


machines that can be accessed online. As an example, the Python environment can be
installed on remote machines hosted by your academic institution (most universities
have computing centers that offer this opportunity) or by commercial providers (often
offering a basic free plan). The concepts and procedures described above for installing
a local Python environment remain valid for remote machines. However, working
with remote machines requires additional skills to access and operate online (e.g.,
knowledge of Secure Shell or Remote Desktop protocols for Linux and Windows-
based machines, respectively). Therefore, to keep things simple, I suggest again
starting with a local installation of the Anaconda Python distribution.
8 1 Setting Up Your Python Environment, Easily

An alternative possibility to start working with Python online without installing a


local environment is to use a remote IDE. For example, commercial providers such
as Repl.it6 and PythonAnywhere7 offer free and complete Python IDEs, allowing the
user to start coding first and later move on to developing more advanced applications.
A drawback of this approach, however, is that neither IDE is specifically designed
for scientific computing. Consequently, running code from this book will require the
installation of additional libraries not included by default in the core distribution.
Therefore, to easily replicate the code and examples given in this book, I suggest,
once again, to locally install the most recent Anaconda Python distribution on your
computer.

1.5 Python Packages for Scientific Applications

A key feature of Python is its modular nature. This section lists a few general-purpose
scientific packages that we will make wide use of in this book. For each library, I
provide with a quick description taken from the official documentation, a link to the
official website and, when possible, a reference for further reading.
NumPy is a Python library that provides a multidimensional array object and an
assortment of routines for fast operations on arrays, including mathematical, logi-
cal, shape manipulation, sorting, selecting, input-output, discrete Fourier transforms,
basic linear algebra, basic statistical operations, random simulations, and other func-
tionalities [3].8
Pandas is an open-source library providing high-performance, easy-to-use data
structures and data-analysis tools for the Python programming language [4].9
SciPy is a collection of mathematical algorithms and functions built on the NumPy
extension of Python. It adds significant power to interactive Python sessions by pro-
viding the user with high-level commands and classes for manipulating and visual-
izing data. With SciPy, an interactive Python session becomes a data-processing and
system-prototyping environment rivaling systems such as MATLAB, IDL, Octave,
R, and SciLab [3].10
Matplotlib is a Python library for creating static, animated, and interactive data
visualizations [2].11
SymPy is a Python library for symbolic mathematics. Symbolic computation deals
with the symbolic computation of mathematical objects. This means that mathemati-

6 https://repl.it.
7 https://www.pythonanywhere.com.
8 https://numpy.org.
9 https://pandas.pydata.org.
10 https://scipy.org.
11 https://matplotlib.org.
1.5 Python Packages for Scientific Applications 9

cal objects are represented exactly, not approximately, and mathematical expressions
with unevaluated variables are left in symbolic form [12].12
Scikit-learn is an open-source machine learning library that supports supervised
and unsupervised learning. It also provides various tools for model fitting, data pre-
processing, model selection and evaluation, and many other utilities [13].13

1.6 Python Packages Specifically Developed for Geologists

Many Python packages have been developed to solve geology problems. They form
a wide, heterogeneous, and useful ecosystem allowing us to achieve specific geology
tasks. Examples include Devito, ObsPy, and Pyrolyte, to cite a few. Most of these
packages can be easily installed by using the Conda package management system.
Others requires a few additional steps and skills. The use of these specific packages
is not covered in the present book, since they are typically developed to solve very
specific geology problems. However, a novice to Python will benefit and probably
require the notions reported in this book to be able to use these packages. Appendix
A and the online repository14 of the book provide a comprehensive list of resources
and Python packages developed to solve geology tasks.

12 https://www.sympy.org.
13 https://scikit-learn.org.
14 https://github.com/petrelli-m/python_earth_science_book.
Chapter 2
Python Essentials for a Geologist

2.1 Start Working with IPython Console

The IPython Console (Fig. 2.1) allows us to execute single instructions, multiple lines
of code, and scripts, all of which may receive output from Python [15].
To start working with the IPython Console, consider Fig. 2.2, where the first
two instructions are A = 1 and B = 2.5. The meaning of these two commands is
straightforward: they simply assign the value of 1 and 2.5 to the variables A and B,
respectively. The third instruction is A + B, which sums the two variables A and B,
obtaining the result 3.5.
Figure 2.2 also provides information about the type of variables in Python
(Fig. 2.3). For numbers, Python supports integers, floating point, and complex num-
bers. Integers and floating-point numbers differ by the presence or absence of deci-
mals. In our case, A is an integer and B is a floating-point number. Complex numbers
have a real part and an imaginary part, and they are not discussed in this book. Oper-
ations like addition or subtraction automatically convert integers into floating-point
numbers if one of the operands (in our case, B) is floating point. The type() function
returns the type of a variable. Additional data types that are relevant for this book
are (a) Boolean (i.e., True or False), (b) Sequences, and (c) Dictionaries.
In Python, a Sequence type is an ordered collection of elements. Examples of
sequences are Strings, Lists, and Tuples. Strings are sequences of characters, Lists
are ordered collections of data, and Tuples are similar to Lists, but they cannot be
modified after their creation. Figure 2.4 shows how to define and access Strings,
Lists, and Tuples.
The elements of a sequence can be accessed by using indexes. In Python, the first
index of a sequence is always 0 (zero). For example, the instruction my_string[0]
returns the first element of my_string defined in Fig. 2.4 (i.e., “M”). Similarly,
my_touple[2] returns the third element of my_touple (i.e., “Maurizio”). Additional
examples on how to access a sequence are reported in Fig. 2.5. Using negative num-
bers (e.g., my_string[−1]), the indexing of the sequences starts from the last element
and proceeds in reverse mode. Two numbers separated by a colon (e.g. [3:7]) define
an index range, sampling the sequence from the lower to the upper bounds, exclud-
ing the upper bound. For the statement my_string[3 : 7], the interpreter samples

© The Author(s), under exclusive license to Springer Nature Switzerland AG 2021 11


M. Petrelli, Introduction to Python in Earth Science Data Analysis,
Springer Textbooks in Earth Sciences, Geography and Environment,
https://doi.org/10.1007/978-3-030-78055-5_2
12 2 Python Essentials for a Geologist

Fig. 2.1 IPython console

Fig. 2.2 Start working with the IPython console

Fig. 2.3 Variable data types in Python


2.1 Start Working with IPython Console 13

Fig. 2.4 Defining and working with sequences

my_string from the third to the seventh indexes (i.e., “name”). Finally, commands
like my_string[: 2] and my_string[11 :] sample my_string from the beginning to
the index 2 (excluded) and from the index 11 to the last element, respectively.
Dictionaries are data types consisting of a collection of key-value pairs. A dic-
tionary can be defined by enclosing a comma-separated list of key-value pairs in
curly braces, with a colon separating each key from the associated value (Fig. 2.6).
In a dictionary, a value is retrieved by specifying the corresponding key in square
brackets (Fig. 2.6).

2.2 Naming and Style Conventions

The main aim of using conventions in programming is to improve the readability of


codes and to facilitate collaboration between different programmers. In Python, the
“PEP 8—Style Guide for Python Code” gives the coding conventions for Python.1
Writing readable code is important for many reasons, the main one of which
is to allow others to easily understand your code. This is crucial when working
on collaborative projects. By sharing best practices, programming teams will write
consistent and elegant codes.
In the book, I try to follow the main rules defined by the PEP 8—Style Guide for
Python Code. Beginners should keep in mind that these guidelines exist and start

1 https://www.python.org/dev/peps/pep-0008/.
14 2 Python Essentials for a Geologist

Fig. 2.5 Accessing sequences

Fig. 2.6 Defining and accessing dictionaries

following the most important ones, which are listed in Table 2.1 for convenience.
However, I suggest that beginners focus more on their results (i.e., achieving the
objectives) than on the form of the code.

2.3 Working with Python Scripts

A script is a sequence of code instructions used to automate processes (e.g., making


a diagram, or a geological model) that would otherwise need to be executed step by
step (e.g., in the IPython console). In detail, Python scripts are text files typically
2.3 Working with Python Scripts 15

Table 2.1 Styling and Naming conventions in Python


Type Style or Naming convention Example
Function Function names should be lowercase, with words Function,
separated by underscores as necessary to improve my_function
readability (cf. Sect. 2.4)
Variable Variable names follow the same convention as function x, my_dataset
names
Constant Constants are usually written in all capital letters with A, GREEK_P
underscores separating words
Class Start each word with a capital letter (CapWords Circle, MyClass
convention). Do not use underscores to separate
subsequent words (cf. appendix B)
Method Use the function naming rules: lowercase with words Method,
separated by underscores as necessary to improve my_method
readability (cf. appendix B)
Names to Never use the characters ’l’ (lowercase letter el), ’O’ –
avoid (uppercase letter oh), or ’I’ (uppercase letter eye) as
single character variable names
Indentation PEP 8 recommends using four spaces per indentation –
level (cf. Sect. 2.4)

characterized by a .py extension and containing a sequence of Python instructions.


Writing and modifying Python scripts requires nothing more than a text editor. Spyder
incorporates a text editor with advanced features such as code completion and syntax
inspection. In Spyder, the text editor is usually positioned in a panel on the left
portion of the screen. To execute a Python script, the interpreter reads each instruction
sequentially, starting from the first line. To execute a Python script in the active
IPython console of Spyder, we click the play button, as shown in Fig. 2.7, or use the
F5 keyboard shortcut. Keyboard shortcuts help us be more proficient; Table 2.2 lists
a few additional keyboard shortcuts.
The script Listing 2.1 gives the Python script of Fig. 2.7 and, in lines 5 to 10, the
output obtained upon running the script in the IPython console.
The three single quotation marks (i.e.,  ) in lines 5 and 10 of the script Listing 2.1
open and close a multi-line comment, which is simply lines of code or text that are
ignored by the interpreter. The symbol # means that the remaining text on the same
line is a comment. Comments are a fundamental part of Python codes because they
help you and future users clarify the code workflow. Keep in mind that you might
spend an entire day developing a very proficient script only to wake up the next
morning without remembering how the script works! Comments are a godsend in
these situations.
In fact, you don’t necessarily need Spyder to write a .py script. As stated above,
Python scripts can be written using any text editor. The python instruction will run
your scripts in the command line or terminal application (see Fig. 2.8).
16 2 Python Essentials for a Geologist

Fig. 2.7 Running a Python script in Spyder

Table 2.2 Selected spyder keyboard shortcuts


Windows OS Mac OS Action
F5 F5 Run file (complete script)
F9 F9 Run selection (or current line)
Ctrl + T Cmd + T Open an IPython console
Ctrl + space Ctrl + space Code completion
Tab Tab Indent selected line(s)
Shift + Tab Shift + Tab Unindent selected line(s)
Ctrl + Q Cmd + Q Quit Spyder

Fig. 2.8 Running a Python script using the python instruction in a MacBook Terminal application
2.3 Working with Python Scripts 17

1 p ri nt ( " P y t h o n i n s t r u c t i o n n .1 " )
2 p ri nt ( " P y t h o n i n s t r u c t i o n n .2 " )
3 p ri nt ( " P y t h o n i n s t r u c t i o n n .3 " )
4
5 ’’’
6 Output :
7 P y t h o n i n s t r u c t i o n n .1
8 P y t h o n i n s t r u c t i o n n .2
9 P y t h o n i n s t r u c t i o n n .3
10 ’’’
Listing 2.1 A simple script in Python

2.4 Conditional Statements, Indentation, Loops,


and Functions

Conditional Statements
In Python, the if statement indicates the conditional execution of single or multiple
instructions based on the value of an expression.

1 my_var = 2
2
3 if m y _ v a r > 2:
4 pr in t ( ’ m y _ v a r is g r e a t e r than 2 ’ )
5 elif m y _ v a r == 2:
6 pr in t ( ’ m y _ v a r is e q u a l to 2 ’ )
7 # more i n s t r u c t i o n s could be added
8 # using the same i n d e n t a t i o n
9 else :
10 p ri nt ( ’ MyVar is less than 2 ’ )
11
12 ’’’
13 Output :
14 m y _ v a r is e q u a l to 2
15 ’’’
Listing 2.2 If, elif, else statements

To understand, consider the script Listing 2.2. At line 1, we define the variable
my_var and assign it the value 2. At line 3, the if statement evaluates my_var and
executes the instruction at line 4 only if my_var is greater than 2. Given that this
is not in this case, the interpreter jumps to line 5 and evaluates whether my_var is
equal to 2. Note that “=” assigns a value to a variable, whereas “==” compares two
quantities, returning “True” if they are equal and “False” if they differ. Given that
my_var equals 2, the interpreter executes the instructions from line 6 to 8. Finally,
18 2 Python Essentials for a Geologist

the instruction at line 10 is executed in all remaining cases (i.e., when my_var is less
than 2).
Indentation and Blocks
The term “indentation” refers to adding one or more white spaces before an instruc-
tion. In a Python script, contiguous instructions (e.g., lines 6 to 8 of the script List-
ing 2.2) that are indented to the same level are considered to be part of the same
block of code. A code block is considered by the interpreter as a single entity, which
allows us to structure Python scripts. For example, the blocks after the if, elif, and
else statements in script Listing 2.2 are executed in accordance with the conditions
given on lines 3, 5, and 9, respectively.
To better understand how indentation works in Python, consider the code List-
ing 2.3. The instructions from line 1 to 3 and at line 12 are always executed each
time we run the script. The interpreter executes the instructions at lines 5, 9, 10, and
11 if and only if the variable a equals 1. Finally, the interpreter executes lines 7 and
8 if and only if a and b equal 1 and 3, respectively.
Note that indentation is a fundamental concept in Python, allowing us to define
simple operations like conditional statements, loops, and functions, but also more
complex structures like modules and packages.

1 # this i n s t r u c t i o n is a l w a y s e x e c u t e d
2 # this i n s t r u c t i o n is a l w a y s e x e c u t e d
3 # this i n s t r u c t i o n is a l w a y s e x e c u t e d
4 if a == 1:
5 # this i n s t r u c t i o n is e x e c u t e d if a = 1
6 if b == 3:
7 # this i n s t r u c t i o n is e x e c u t e d if a = 1 and b = 3
8 # this i n s t r u c t i o n is e x e c u t e d if a = 1 and b = 3
9 # this i n s t r u c t i o n is e x e c u t e d if a = 1
10 # this i n s t r u c t i o n is e x e c u t e d if a = 1
11 # this i n s t r u c t i o n is e x e c u t e d if a = 1
12 # this i n s t r u c t i o n is a l w a y s e x e c u t e d
Listing 2.3 Python uses indentation to define blocks of code

For Loops
The for loop in Python iterates over a sequence (i.e., lists, tuples, and strings) or other
iterable objects. As an example, the code Listing 2.4 iterates over the list named rocks.
At line 1 we define a list (i.e., rocks), at line 3 we implement the iteration, and at
line 4 we print to the screen the result of each iteration, namely, each element of the
sequence.
Often, we perform iterations using range(). The command range() is a Python
function that returns a sequence of integers.
The range syntax is range(start, stop, step) where the arguments start, stop, and
step are the initial, final, and step values of the sequence, respectively. Note that the
upper limit (i.e., stop) is not included in the sequence. If we pass only one argument
to the range function [e.g., range(6)], it is interpreted as the stop parameter, with the
2.4 Conditional Statements, Indentation, Loops, and Functions 19

sequence starting from 0. The code Listing 2.5 shows some examples of iterations
over sequences of numbers generated using the range() function.

1 ro ck s = [ ’ s e d i m e n t a r y ’ , ’ i g n e o u s i n t r u s i v e ’ , ’ i g n e o u s
effusive ’, ’ methamorphic ’]
2
3 for rock in rocks :
4 pr in t ( rock )
5
6 ’’’
7 Output :
8 sedimentary
9 igneous intrusive
10 igneous effusive
11 methamorphic
12 ’’’
Listing 2.4 Iterate over a list

1 pr in t ( ’a s e q u e n c e from 0 to 2 ’ )
2 for i in range (3) :
3 pr in t ( i )
4
5 pr in t ( ’ - - - - - - - - - - - - - - - - - - - - - - ’ )
6 pr in t ( ’a s e q u e n c e from 2 to 4 ’ )
7 for i in range (2 , 5) :
8 pr in t ( i )
9
10 pr in t ( ’ - - - - - - - - - - - - - - - - - - - - - - ’ )
11 pr in t ( ’a s e q u e n c e from 2 to 8 with a step of 2 ’ )
12 for i in range (2 , 9 , 2) :
13 p ri nt ( i )
14
15 ’’’
16 Output :
17 a s e q u e n c e from 0 to 2
18 0
19 1
20 2
21 ----------------------
22 a s e q u e n c e from 2 to 4
23 2
24 3
25 4
26 ----------------------
27 a s e q u e n c e from 2 to 8 with a step of 2
28 2
29 4
30 6
31 8
32 ’’’
Listing 2.5 Iterating over a sequence of numbers generated using range()
Discovering Diverse Content Through
Random Scribd Documents
XIV
PRISONERS OF STATE AT BORO BOEDOR

The fact is not generally appreciated that there are ruins of Buddhist
and Brahmanic temples in Middle Java surpassing in extent and
magnificence anything to be seen in Egypt or India. There, in the
heart of the steaming tropics, in that summer land of the world below
the equator, on an island where volcanoes cluster more thickly and
vegetation is richer than in any other region of the globe, where
earthquakes continually rock and shatter, and where deluges
descend during the rainy half of the year, remains nearly intact the
temple of Boro Boedor, covering almost the same area as the Great
Pyramid of Gizeh. It is ornamented with hundreds of life-size statues
and miles of bas-reliefs presenting the highest examples of Greco-
Buddhist art—a sculptured record of all the arts and industries, the
culture and civilization, of the golden age of Java, of the life of the
seventh, eighth, and ninth centuries in all the farther East—a record
that is not written in hieroglyphs, but in plainest pictures carved by
sculptor’s chisel. That solid pyramidal temple, rising in magnificent
sculptured terraces, that was built without mortar or cement, without
column or pillar or arch, is one of the surviving wonders of the world.
On the spot it seems a veritable miracle.
It is one of the romances of Buddhism that this splendid
monument of human industry, abandoned by its worshipers as one
cult succeeded another, and forgotten after the Mohammedan
conquest imposed yet another creed upon the people, should have
disappeared completely, hidden in the tangle of tropical vegetation, a
formless, nameless, unsuspected mound in the heart of a jungle, lost
in every way, with no part in the life of the land, finally to be
uncovered to the sight of the nineteenth century. When Sir Stamford
Raffles came as British governor of Java in 1811, the Dutch had
possessed the island for two centuries, but in their greed for gulden
had paid no heed to the people, and knew nothing of that earlier time
before the conquest when the island was all one empire, the arts and
literature flourished, and, inspired by Hindu influence, Javanese
civilization reached its highest estate; nor did the Hollander allow any
alien investigators to peer about this profitable plantation. Sir
Stamford Raffles, in his five years of control, did a century’s work. He
explored, excavated, and surveyed the ruined temples, and
searching the voluminous archives of the native princes, drew from
the mass of romantic legends and poetic records the first “History of
Java.” His officers copied and deciphered inscriptions, and gradually
worked out all the history of the great ruins, and determined the date
of their erection at the beginning of the seventh century.
At this time Sir Stamford wrote: “The interior of Java contains
temples that, as works of labor and art, dwarf to nothing all our
wonder and admiration at the pyramids of Egypt.” Then Alfred
Russel Wallace said: “The number and beauty of the architectural
remains in Java ... far surpass those of Central America, and
perhaps even those of India.” And of Boro Boedor he wrote: “The
amount of human labor and skill expended on the Great Pyramid of
Egypt sinks into insignificance when compared with that required to
complete this sculptured hill-temple in the interior of Java.” Herr
Brumund called Boro Boedor “the most remarkable and magnificent
monument Buddhism has ever erected”; and Fergusson, in his
“History of Indian and Eastern Architecture,” finds in that edifice the
highest development of Buddhist art, an epitome of all its arts and
ritual, and the culmination of the architectural style which, originating
at Barhut a thousand years before, had begun to decay in India at
the time the colonists were erecting this masterpiece of the ages in
the heart of Java.
There is yet no Baedeker, or Murray, or local red book to lead one
to and about the temples and present every dry detail of fact. The
references to the ruins in books of travel and general literature are
vague or cautious generalities, absurd misstatements, or guesses. In
the great libraries of the world’s capitals the archæologists’ reports
are rare, and on the island only Dutch editions are available.
Fergusson is one’s only portable guide and aid to understanding; but
as he never visited the stupendous ruin, his is but a formal record of
the main facts. Dutch scientists criticize Sir Stamford Raffles’s work
and all that Von Humboldt and Lassen deduced from it concerning
Javanese religion and mythology. They entirely put aside all native
histories and traditions, searching and accepting only Chinese and
Arabic works, and making a close study of ancient inscriptions, upon
the rendering of which few of the Dutch savants agree.
We had applied for new toelatings-kaarten, or admission tickets, to
the interior of the island; and as they had not arrived by the
afternoon before we intended leaving Buitenzorg, we drove to the
assistant resident’s to inquire. “You shall have them this evening,”
said that gracious and courtly official, standing beside the huge
carriage; “but as it is only the merest matter of form, go right along in
the morning, ladies, anyhow, and I shall send the papers after you by
post. To Tissak Malaya? No? Well, then, to Djokjakarta.”
Upon that advice we proceeded on our journey, crossed the
Preangers, saw the plain of Leles, and made our brief visit to Tissak
Malaya. We rode for a long, hot day across the swamps and low-
lying jungles of the terra ingrata of Middle Java, and just before
sunset we reached Djokjakarta, a provincial capital, where the native
sultan resides in great state, but poor imitation of independent
rulership. We had tea served us under the great portico of the Hotel
Toegoe, our every movement followed by the uncivilized piazza stare
of some Dutch residents—that gaze of the summer hotel that has no
geographic or racial limit, which even occurs on the American littoral,
and in Java has a fixedness born of stolid Dutch ancestry, and an
intensity due to the tropical fervor of the thermometer, that put it far
beyond all other species of unwinking scrutiny. The bovine, ruminant
gaze of those stout women, continued and continued past all
provincial-colonial curiosity as to the cut and stuff of our gowns,
drove us to the garden paths, already twinkling with fireflies. The
landlord joined us there, and strolled with us out to the street and
along a line of torch-lighted booths and shops, where native products
and native life were most picturesquely presented. Our landlord
made himself very agreeable in explaining it all, walked on as far as
the gates of the sultan’s palace, plying us with the most point-blank
personal questions, our whence, whither, why, for how long, etc.; but
we did not mind that in a land of stares and interrogative English. He
showed us the carriage we could have for the next day’s twenty-five-
mile drive to Boro Boedor—“if you go,” with quite unnecessary
emphasis on the phrase of doubt. He finally brought us back to the
portico, disappeared for a time, and returning, said: “Ladies, the
assistant resident wishes to meet you. Will you come this way?” And
the courteous one conducted us through lofty halls and porticos to
his own half-office parlor, all of us pleased at this unexpected
attention from the provincial official.
A tall, grim, severe man in the dark cloth clothes of ceremony, with
uniform buttons, waved a semi-military cap, and said curtly: “Ladies,
it is my duty to inform you that you have no permission to visit
Djokja.”
It took some repetitions for us to get the whole sensation of the
heavens suddenly falling on us, to learn that a telegram had come
from official headquarters at Buitenzorg to warn him that three
American ladies would arrive that afternoon, without passports, to
visit Djokja.
“Certainly not, because those Buitenzorg officials told us not to
wait for the passports—that they would mail them after us.” Then
ensued the most farcical scene, a grand burlesque rendering of the
act of apprehending criminals, or rather political suspects. The
assistant resident tried to maintain the stern, judicial manner of a
police-court magistrate, cross-examining us as closely as if it were
testimony in a murder trial we were giving, and was not at all inclined
to admit that there could be any mistake in the elaborately perfect
system of Dutch colonial government. Magnificently he told us that
we could not remain in Djokja, and we assured him that we had no
wish to do so, that we were leaving for Boro Boedor in the morning.
The Pickwickian message from Buitenzorg had not given any
instructions. It merely related that we should arrive. We had arrived,
and the assistant resident evidently did not know just what to do
next. At any rate, he intended that we should stand in awe of him
and the government of Netherlands India. He “supposed” that it was
intended that we should be sent straight back to Buitenzorg. We
demurred, in fact refused—the two inflammable, impolitic ones of us,
who paid no heed to the gentle, gray-haired elder member of our
party, who was all resignation and humility before the terrible official.
We produced our United States passports, and quite as much as told
him that he and the noble army of Dutch officials might finish the
discussion with the American consul; we had other affairs, and were
bound for Boro Boedor. He waved the United States passports
aside, curtly said they were of “no account,” examined the letters of
credit with a shade more of interest, and gave his whole attention to
my “Smithsonian passport,” or general letter “to all friends of
science.” That beautifully written document, with its measured
phrases, many polysyllabic words in capital letters, and the big gold
seal of Saint-Gaudens’s designing, worked a spell; and after slowly
reading all the commendatory sentences of that great American
institution “for the increase and diffusion of knowledge among men,”
he read it again:
“Hum-m-m! Hum-m-m! The Smithsonian Institution of Washington
—National Geographic Society—scientific observation and study—
anthropology—photography—G. Brown Goode, acting secretary! Ah,
ladies, since you have such credentials as this,”—evidently the
Smithsonian Institution has better standing abroad than the
Department of State, and G. Brown Goode, acting secretary of the
one, was a better name to conjure with away from home than Walter
Q. Gresham, actual secretary of the other,—“since you come so
highly commended to us, I will allow you to proceed to Boro Boedor,
and remain there while I report to Buitenzorg and ask for
instructions. You will go to Boro Boedor as early as possible in the
morning,” he commanded, and then asked, “How long had you
intended to remain there?”
“That depends. If it is comfortable, and the rains keep off, we may
stay several days. If not, we return to-morrow evening.”
“No, no, no!” he cried in alarm; “you must stay there at Boro
Boedor. You have no permission to visit Djokja, and I cannot let you
stay in my residency. You must stay at Boro Boedor or go back to
Buitenzorg.”
To be ordered off to the Buddhist shrine at sunrise put the
pilgrimage in quite another light; to be sentenced to Nirvana by a
local magistrate in brass buttons was not like arriving there by slow
stages—meditation and reincarnation; but as the assistant resident
seemed to be on the point of repenting his clemency, we
acquiesced, and the great man and his minions drove away, the
bearer of the pajong, or official umbrella of his rank, testifying to the
formal character of the visit he had been paying. The landlord
mopped his brow, sighed, and looked like one who had survived
great perils; and we then saw that his sightseeing stroll down the
street with us had been a ruse, a little clever scouting, a preliminary
reconnaissance for the benefit of the puzzled magistrate.
We left Djokja at sunrise, with enthusiasm somewhat dampened
from former anticipations of that twenty-five-mile drive to Boro
Boedor, “the aged thing” in the Boro district of Kedu Residency, or
Bára Budha, “Great Buddha.” We had expected to realize a little of
the pleasure of travel during the barely ended posting days on this
garden island, networked over with smooth park drives all shaded
with tamarind-, kanari-, teak-, and waringen-trees, and it proved a
half-day of the greatest interest and enjoyment. Our canopied
carriage was drawn by four little rats of ponies, driven by a serious
old coachman in a gay sarong and military jacket, with a huge
lacquered vizor or crownless hat tied on over his battek turban, like a
student’s exaggerated eye-shade. This gave the shadow of great
dignity and owlish wisdom to his wrinkled face, ornamented by a
mustache as sparsely and symmetrically planted as walrus whiskers.
He held the reins and said nothing. When there was anything to do,
the running footman did it—a lithe little creature who clung to a rear
step, and took to his heels every few minutes to crack the whip over
the ponies’ heads, and with a frenzied “Gree! G-r-r-ee! Gr-r-r-e-e-e!”
urge the mites to a more breakneck gallop in harness. He steered
them by the traces as he galloped beside them, guided them over
bridges, around corners, past other vehicles, and through crowds,
while the driver held the reins and chewed betel tobacco in
unconcerned state. We rocked and rolled through beautiful arched
avenues, with this bare-legged boy in gay petticoat “gr-r-ree-ing” us
along like mad, people scattering aside like frightened chickens, and
kneeling as we passed by. The way was fenced and hedged and
finished, to each blade of grass, like some aristocratic suburb of a
great capital, an endless park, or continuous estate, where fancy
farming and landscape-gardening had gone their most extravagant
lengths. There was not a neglected acre on either side for all the
twenty-five miles; every field was cultivated like a tulip-bed; every
plant was as green and perfect as if entered in a horticultural show.
Streams, ravines, and ditches were solidly bridged, each with its
white cement parapet and smooth concrete flooring, and each
numbered and marked with Dutch preciseness; and along every bit
of the road were posted the names of the kampongs and estates
charged to maintain the highway in its perfect condition. Telegraph-
and telephone-wires were strung on the rigid arms of cotton-trees,
and giant creepers wove solid fences as they were trained from tree-
trunk to tree-trunk—the tropics tamed, combed, and curbed, hitched
to the cart of commerce and made man’s abject servant.
Every few miles there were open red-tiled pavilions built over the
highways as refuges for man and beast from the scorching sun of
one season and the cloud-burst showers of the rainy half of the year.
Twice we found busy passers going on in groves beside these rest-
houses—picturesque gatherings of men, women, and children, and
displays of fowls, fruits, nuts, vegetables, grain, sugar, spices, gums,
and flowers, that tempted one to linger and enjoy, and to photograph
every foot of the passer’s area. The main road was crowded all the
way like a city street, and around these passers the highway
hummed with voices. One can believe in the density of the
population—450 to the square mile[4]—when he sees the people
trooping along these country roads; and he can well understand why
every foot of land is cultivated, how even in the benevolent land of
the banana every one must produce something, must work or starve.
The better sanitary condition of the native kampongs is given as a
great factor in the remarkable increase of population in the last half-
century; but it took many years of precept and example, strict laws,
and a rating of native rulers and village chiefs according to the
cleanliness of their kampongs, before the native hamlets became
tropical counterparts of Broek and the other absurdly clean towns of
Holland. These careless children of the tropics are obliged to
whitewash their houses twice a year, look to their drains and debris,
and use disinfectants; and with the dainty little basket houses, one of
which may be bought outright for five dollars, and the beautiful palms
and shrubberies to serve as screens from rice-field vapors, each little
kampong is a delight in every way.

WAYSIDE PAVILION ON POST-ROAD.

Men and boys toiled to the passer, bent over with the weight of
one or two monstrous jack-fruits or durians on their backs. A woman
with a baby swinging in the slandang over her shoulder had tied
cackling chickens to the back of her belt, and trudged on comfortably
under her umbrella; and a boy swung a brace of ducks from each
end of a shoulder-pole, and trotted gaily to the passer. The
kampongs, or villages, when not hidden in palm- and plantain-groves
behind fancy bamboo fences, were rows of open houses on each
side of the highway, and we reviewed native life at leisure while the
ponies were changed. The friendly, gentle little brown people
welcomed us with amused and embarrassed smiles when our
curiosity as to sarong-painting, lacquering, and mat-weaving carried
us into the family circle. The dark, round-eyed, star-eyed babies and
children showed no fear or shyness, and the tiniest ones—their soft
little warm brown bodies bare of ever a garment save the cotton
slandang in which they cuddle so confidingly under the mother’s
protecting arm—let us lift and carry and play with them at will.
We left the main road, and progressed by a narrower way between
open fields of pepper, manioc, indigo, and tobacco, with picturesque
views of the three symmetrical and beautiful mountains, Soembung,
Merbaboe, and Merapi—the first and largest one as pure in line, as
exquisite and ideal a peak, as Fujiyama, and the others sloping
splendidly in soft volcanic outlines. Soembung is the very center of
Java, and native legends cling to the little hill of Tidar at its base—
the “spike of the universe,” the nail which fastens the lovely island to
the face of the earth. Merbaboe, the “ash-ejecting,” has wrought ruin
in its time, and a faint white plume of steam waves from its summit
still. The capitulations which delivered the Napoleonic possessions
of the Dutch East Indies to England in 1811 were signed at the base
of Merbaboe, and in our then frame of mind toward the Dutch
government we wished to make a pilgrimage of joyous celebration to
the spot. The third of the graceful peaks, Merapi, the “fire-throwing,”
was a sacred peak in Buddhist times, when cave-temples were hewn
in its solid rock and their interiors fretted over with fine bas-reliefs. A
group of people transplanting rice, a little boy driving a flock of geese
down the road, a little open-timbered temple of the dead in a
frangipani-grove—all these, with the softly blue-and-purple
mountains in the background, are pictures in enduring memory of
that morning’s ride toward Nirvana.
A gray ruin showed indistinctly on a hilltop, and after a run through
a long, arched avenue we came out suddenly at the base of the hill-
temple. Instead of a mad, triumphant sweep around the great
pyramid, the ponies balked, rooted themselves past any lashing or
“gr-r-ree-ing,” and we got out and walked under the noonday sun,
around the hoary high altar of Buddha, down an avenue of tall
kanari-trees, lined with statues, gargoyles, and other such recha, or
remains of ancient art, to the passagrahan, or government rest-
house.
XV
BORO BOEDOR

The deep portico of the passagrahan commands an angle and two


sides of the square temple, and from the mass of blackened and
bleached stones the eye finally arranges and follows out the broken
lines of the terraced pyramid, covered with such a wealth of
ornament as no other one structure in the world presents. The first
near view is almost disappointing. In the blur of details it is difficult to
realize the vast proportions of this twelve-century-old structure—a
pyramid the base platform of which is five hundred feet square, the
first terrace walls three hundred feet square, and the final dome one
hundred feet in height. Stripped of every kindly relief of vine and
moss, every gap and ruined angle visible, there was something
garish, raw, and almost disordered at the first glance, almost as
jarring as newness, and the hard black-and-white effect of the dark
lichens on the gray trachyte made it look like a bad photograph of
the pile. The temple stands on a broad platform, and rises first in five
square terraces, inclosing galleries, or processional paths, between
their walls, which are covered on each side with bas-relief
sculptures. If placed in single line these bas-reliefs would extend for
three miles. The terrace walls hold four hundred and thirty-six niches
or alcove chapels, where life-size Buddhas sit serene upon lotus
cushions. Staircases ascend in straight lines from each of the four
sides, passing under stepped or pointed arches the keystones of
which are elaborately carved masks, and rows of sockets in the
jambs show where wood or metal doors once swung. Above the
square terraces are three circular terraces, where seventy-two
latticed dagobas (reliquaries in the shape of the calyx or bud of the
lotus) inclose each a seated image, seventy-two more Buddhas
sitting in these inner, upper circles of Nirvana, facing a great dagoba,
or final cupola, the exact function or purpose of which as key to the
whole structure is still the puzzle of archæologists. This final shrine is
fifty feet in diameter, and either covered a relic of Buddha, or a
central well where the ashes of priests and princes were deposited,
or is a form surviving from the tree-temples of the earliest, primitive
East when nature-worship prevailed. The English engineers made
an opening in the solid exterior, and found an unfinished statue of
Buddha on a platform over a deep well-hole; and its head, half
buried in debris, still smiles upon one from the deep cavern. M.
Freidrich, in “L’Extrême Orient” (1878), states that this top dagoba
was opened in the time of the resident Hartman (1835), and that gold
ornaments were found; and it was believed that there were several
stories or chambers to this well, which reached to the lowest level of
the structure. M. Désiré de Charnay, who spent an afternoon at Boro
Boedor in 1878 in studying the resemblance of the pyramid temples
of Java to those of Central America, believed this well-hole to be the
place of concealment for the priest whose voice used to issue as a
mysterious oracle from the statue itself.

BORO BOEDOR. FROM THE PASSAGRAHAN


A staircase has been constructed to the summit of this dagoba,
and from it one looks down upon the whole structure as on a ground-
plan drawing, and out over finely cultivated fields and thick palm-
groves to the matchless peaks and the nearer hills that inclose this
fertile valley of the Boro Boedor—“the very finest view I ever saw,”
wrote Marianne North.
Three fourths of the terrace chapels and the upper dagobas have
crumbled; hundreds of statues are headless, armless, overturned,
missing; tees, or finials, are gone from the bell-roofs; terrace walls
bulge, lean outward, and have fallen in long stretches; and the
circular platforms and the processional paths undulate as if
earthquake-waves were at the moment rocking the mass. No cement
was used to hold the fitted stones together, and another Hindu
peculiarity of construction is the entire absence of a column, a pillar,
or an arch. Vegetation wrought great ruin during its buried centuries,
but earthquakes and tropical rains are working now a slow but surer
ruin that will leave little of Boro Boedor for the next century’s wonder-
seekers, unless the walls are soon straightened and strongly braced.
GROUND-PLAN OF BORO BOEDOR.

All this ruined splendor and wrecked magnificence soon has an


overpowering effect on one. He almost hesitates to attempt studying
out all the details, the intricate symbolism and decoration lavished by
those Hindus, who, like the Moguls, “built like Titans, but finished like
jewelers.” One walks around and around the sculptured terraces,
where the bas-reliefs portray all the life of Buddha and his disciples,
and the history of that great religion—a picture-Bible of Buddhism.
All the events in the life of Prince Siddhartha, Gautama Buddha, are
followed in turn: his birth and education, his leaving home, his
meditation under Gaya’s immortal tree, his teaching in the deer-park,
his sitting in judgment, weighing even the birds in his scales, his
death and entrance into Nirvana. The every-day life of the seventh
and eighth century is pictured, too—temples, palaces, thrones and
tombs, ships and houses, all of man’s constructions, are portrayed.
The life in courts and palaces, in fields and villages, is all seen there.
Royal folk in wonderful jewels sit enthroned, with minions offering
gifts and burning incense before them, warriors kneeling, and
maidens dancing. The peasant plows the rice-fields with the same
wooden stick and ungainly buffalo, and carries the rice-sheaves from
the harvest-field with the same shoulder-poles, used in all the farther
East to-day. Women fill their water-vessels at the tanks and bear
them away on their heads as in India now, and scores of bas-reliefs
show the unchanging customs of the East that offer sculptors the
same models in this century. Half the wonders of that great three-
mile-long gallery of sculptures cannot be recalled. Each round
disclosed some more wonderful picture, some more eloquent story,
told in the coarse trachyte rock furnished by the volcanoes across
the valley. Even the humorous fancies of the sculptors are expressed
in stone. In one rilievo a splendidly caparisoned state elephant flings
its feet in imitation of the dancing-girl near by. Other sportive
elephants carry fans and state umbrellas in their trunks; and the
marine monsters swimming about the ship that bears the Buddhist
missionaries to the isles have such expression and human
resemblance as to make one wonder if those primitives did not
occasionally pillory an enemy with their chisels, too. In the last
gallery, where, in the progress of the religion, it took on many
features of Jainism, or advancing Brahmanism, Buddha is several
times represented as the ninth avatar, or incarnation, of Vishnu, still
seated on the lotus cushion, and holding a lotus with one of his four
hands. Figure after figure wears the Brahmanic cord, or sacrificial
thread, over the left shoulder; and all the royal ones sit in what must
have been the pose of high fashion at that time—one knee bent
under in tailor fashion, the other bent knee raised and held in a loop
of the girdle confining the sarong skirt. There is not a grotesque nor
a nude figure in the whole three miles of sculptured scenes, and the
costumes are a study in themselves; likewise the elaborate jewels
which Maia and her maids and the princely ones wear. The trees and
flowers are a sufficient study alone; and on my last morning at Boro
Boedor I made the whole round at sunrise, looking specially at the
wonderful palms, bamboos, frangipani-, mango-, mangosteen-,
breadfruit-, pomegranate-, banana-, and bo-trees—every local form
being gracefully conventionalized, and, as Fergusson says,
“complicated and refined beyond any examples known in India.” It is
such special rounds that give one a full idea of what a monumental
masterpiece the great Buddhist vihara is, what an epitome of all the
arts and civilization of the eighth century a. d. those galleries of
sculpture hold, and turn one to dreaming of the builders and their
times.
No particularly Javanese types of face or figure are represented.
All the countenances are Hindu, Hindu-Caucasian, and pure Greek;
and none of the objects or accessories depicted with them are those
of an uncivilized people. All the art and culture, the highest standards
of Hindu taste and living, in the tenth century of triumphant
Buddhism, are expressed in this sculptured record of the golden age
of Java. The Boro Boedor sculptures are finer examples of the
Greco-Buddhist art of the times than those of Amravati and
Gandahara as one sees them in Indian museums; and the pure
Greek countenances show sufficient evidence of Bactrian influences
on the Indus, whence the builders came.
Of the more than five hundred statues of Buddha enshrined in
niches and latticed dagobas, all, save the one mysterious figure
standing in the central or summit dagoba, are seated on lotus
cushions. Those of the terrace rows of chapels face outward to the
four points of the compass, and those of the three circular platforms
face inward to the hidden, mysterious one. All are alike save in the
position of the hands, and those of the terrace chapels have four
different poses accordingly as they face the cardinal points. As they
are conventionally represented, there is Buddha teaching, with his
open palm resting on one knee; Buddha learning, with that hand
intently closed; Buddha meditating, with both hands open on his
knees; Buddha believing and convinced, expounding the lotus law
with upraised hand; and Buddha demonstrating and explaining, with
thumbs and index-fingers touching. The images in the lotus bells of
the circular platforms hold the right palm curved like a shell over the
fingers of the left hand—the Buddha who has comprehended, and
sits meditating in stages of Nirvana. It was never intended that
worshipers should know the mien of the great one in the summit
chalice, the serene one who, having attained the supreme end, was
left to brood alone, inaccessible, shut out from, beyond all the world.
For this reason it is believed that this standing statue was left
incomplete, the profane chisel not daring to render every accessory
and attribute as with the lesser ones.
FOUR BAS-RELIEFS FROM BORO BOEDOR.

After Wilsen’s drawings.

Humboldt first noted the five different attitudes of the seated


figures, and their likeness to the five Dhyani Buddhas of Nepal; and
the discovery of a tablet in Sumatra recording the erection of a
seven-story vihara to the Dhyani Buddha was proof that the faith that
first came pure from the mouth of the Oxus and the Indus must have
received later bent through missionaries from the Malay Peninsula
and Tibet. The Boro Boedor images have the same lotus cushion
and aureole, the same curls of hair, but not the long ears of the
Nepal Buddhas, who in the Mongol doctrine had each his own
paradise or quarter of the earth. The first Dhyani, who rules the
paradise of the Orient, is always represented in the same attitude
and pose of the hands as the image in the latticed bells of these
upper, circular or Nirvana terraces of Boro Boedor. The images on
the east side of Boro Boeder’s square terraces correspond to the
second Dhyani’s conventional pose; those on the south walls, to the
third Dhyani; the west-facing ones, to the fourth Dhyani; and the
northern ones, to the fifth Dhyani of Nepal.
There are no inscriptions visible anywhere in this mass of picture-
writings, no corner-stone or any clue to the exact year of its
founding. We know certainly that the third great synod of Buddhists
in Asoka’s time, 264 b. c., resolved to spread Buddhism abroad, and
that the propaganda begun in Ceylon was carried in every direction,
and that Asoka opened seven of the eight original dagobas of India
enshrining relics of Buddha’s body, and, subdividing, put them in
eighty-four thousand vases or precious boxes, that were scattered to
the limits of that religious world. Stupas, or dagobas, were built over
these holy bits, and all the central dagoba of Boro Boedor is believed
to have been the original structure built over some such reliquary,
and afterward surrounded by the great sculptured terraces. Fa Hian,
the Chinese pilgrim who visited Java in 414 a. d., remarked upon the
number of “heretics and Brahmans” living there, and noted that “the
law of Buddha is not much known.” Native records tell that in 603 a.
d. the Prince of Gujerat came, with five thousand followers in one
hundred and six ships, and settled at Mataram, where two thousand
more men of Gujerat joined him, and a great Buddhist empire
succeeded that of the Brahmanic faith. An inscription found in
Sumatra, bearing date 656 a. d., gives the name of Maha Raja
Adiraja Adityadharma, King of Prathama (Great Java), a worshiper of
the five Dhyani Buddhas, who had erected a great seven-storied
vihara, evidently this one of Boro Boedor, in their honor. This golden
age of the Buddhist empire in Java lasted through the seventh,
eighth, and ninth centuries. Arts and religion had already entered
their decline in the tenth century, when the Prince Dewa Kosoumi
sent his daughter and four sons to India to study religion and the
arts. The princelings returned with artists, soldiers, and many
trophies and products; but this last fresh importation did not arrest
the decay of the faith, and the people, relapsing peaceably into
Brahmanism, deserted their old temples. With the Mohammedan
conquest of 1475-79 the people in turn forsook the worship of Siva,
Durga, and Ganesha, and abandoned their shrines at Brambanam
and elsewhere, as they had withdrawn from Boro Boedor and
Chandi Sewou.
ON THE SECOND TERRACE.

When the British engineers came to Boro Boedor, in 1814, the


inhabitants of the nearest village had no knowledge or traditions of
this noblest monument Buddhism ever reared. Ever since their
fathers had moved there from another district it had been only a tree-

You might also like