📄 Page
1
(This page has no text content)
📄 Page
2
(This page has no text content)
📄 Page
3
PRAISE FOR PRACTICAL JULIA “As a career computational physicist and early participant in the Julia community, Lee has had a front row seat to the development of the Julia ecosystem. He has written numerous technical articles on Julia, and has a great skill in explaining complex topics in a simple way. This book is a great starting point for the reader’s journey into Julia—with the first part covering the fundamentals of the language and second part diving into a variety of different scientific disciplines.” —VIRAL SHAH, CO-CREATOR OF THE JULIA PROGRAMMING LANGUAGE AND CEO OF JULIAHUB “This is a nice deep dive which covers a lot of ground, from the basics on how to define arrays and use the type system all the way to biochemical modeling and scientific machine learning. Lee gives a very nice in-depth treatment, showing not only the most standard ways to do things, but also some different library options along with a good explanation of the pros and cons to the choices. I think this is a great book for any Julia user’s shelf.” —CHRISTOPHER RACKAUCKAS, RESEARCH AFFILIATE AND CO-PI OF THE JULIA LAB, DIRECTOR OF MODELING AND SIMULATION AT JULIA COMPUTING, AND APPLIED MATHEMATICS INSTRUCTOR AT MIT
📄 Page
4
PRACTICAL JULIA A Hands-On Introduction for Scientific Minds by Lee Phillips San Francisco
📄 Page
5
PRACTICAL JULIA. Copyright © 2024 by Lee Phillips. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. First printing 27 26 25 24 23 1 2 3 4 5 ISBN-13: 978-1-7185-0276-5 (print) ISBN-13: 978-1-7185-0277-2 (ebook) Publisher: William Pollock Managing Editor: Jill Franklin Production Manager: Sabrina Plomitallo-González Production Editor: Miles Bond Developmental Editor: Jill Franklin Cover Illustrator: Gina Redman Interior Design: Octopod Studios Technical Reviewer: James Foster Copyeditor: George Hale Proofreader: Audrey Doyle For information on distribution, bulk sales, corporate sales, or translations, please contact No Starch Press® directly at info@nostarch.com or: No Starch Press, Inc. 245 8th Street, San Francisco, CA 94103 phone: 1.415.863.9900 www.nostarch.com Library of Congress Control Number: 2023016515 No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
📄 Page
6
To Gianna and Maxwell
📄 Page
7
About the Author Lee Phillips was a theoretical and computational physicist at the Naval Research Laboratory for 21 years. He has presented his research in numerous scientific papers and at international conferences. He has also written many popular articles on science and its history, and on the use of computers in research. He’s involved with science education and outreach, including serving on the Board of Directors of the Friends of Arlington’s Planetarium and maintaining their website.
📄 Page
8
About the Technical Reviewer James Foster is an applied mathematician with a doctorate in mathematical optimization, specializing in the modeling and optimal planning of energy systems. He has worked across industry and government, and taught both pure and applied mathematics courses at the university level. An enthusiastic contributor to the open source community, he is particularly involved in the development of the JuMP modeling language for optimization in Julia. He also serves as a Carpentries instructor and lesson maintainer, teaching foundational computational skills to researchers.
📄 Page
9
BRIEF CONTENTS Acknowledgments Introduction PART I: LEARNING JULIA Chapter 1: Getting Started Chapter 2: Language Basics Chapter 3: Modules and Packages Chapter 4: The Plotting System Chapter 5: Collections Chapter 6: Functions, Metaprogramming, and Errors Chapter 7: Diagrams and Animations Chapter 8: The Type System PART II: APPLICATIONS Chapter 9: Physics Chapter 10: Statistics Chapter 11: Biology Chapter 12: Mathematics Chapter 13: Scientific Machine Learning Chapter 14: Signal and Image Processing Chapter 15: Parallel Processing Index
📄 Page
10
CONTENTS IN DETAIL ACKNOWLEDGMENTS INTRODUCTION Why Is Julia Popular with Scientists? What Will This Book Do for You? How to Use This Book Book Overview PART I LEARNING JULIA 1 GETTING STARTED Installation Guide Hardware Requirements Prerequisites Julia Versions Installation Privacy Note The Julia Coding Environment The Julia REPL Text Editors Jupyter Notebooks Pluto: A Better Notebook Integrated Development Environments Recommendations 2
📄 Page
11
LANGUAGE BASICS The Syntax: Data Types, Expressions, and Blocks Types of Numbers Operations and Expressions Logic Looping: while Blocks if Blocks Arrays Ranges Arrays: Beyond the First Dimension Tuples Membership Strings and Characters Characters Strings More Looping: for Blocks Functions Composing Functions Creating Anonymous Functions Broadcasting Scope Scoping Rules for Functions Scoping Rules for Loops Modification of Scoping Rules in Interactive Contexts Mutability Functions That Mutate Their Arguments Strings Are Immutable Comments in Code Congratulations 3 MODULES AND PACKAGES Modules
📄 Page
12
Understanding Namespaces Using Installed Modules Selective Importing and Renaming Creating Modules Documenting Functions with Docstrings The Package System How to Add and Remove Packages The Load Path The Nature of a Package The Benefits of Packages How to Create Packages Julia and Git The Relationship Between Package Versions and Git Commits Version Updating and Pinning How to Find Public Packages Conclusion 4 THE PLOTTING SYSTEM Plots The Backend System Modes of Interaction with Plots 2D Plots Plotting from Vectors Plotting Functions Plotting Vectors of Vectors or Functions Displaying and Mutating Creating Parametric Plots Making Polar Plots Making Scatterplots Optional and Keyword Arguments Basic Plot Settings
📄 Page
13
Font Attributes The Frame Styles Working with Plot Settings Aspect Ratio and Title Font Size Labels and Legend Positioning LaTeX Titles and Label Positioning by Data Regression Lines Saving Plots Detail Insets 3D Plots Surface Plots Heatmaps Contour Plots 3D Parametric Plots Vector Plots 3D Scatterplots Useful Backends UnicodePlots PyPlot PlotlyJS PGFPlots and PGFPlotsX HDF5 Gaston Layouts Making Simple Rectangular Layouts Using grid() Creating Complex Layouts Using @layout Conclusion 5 COLLECTIONS Controlling Loop Execution The break Statement
📄 Page
14
The continue Statement Comprehensions and Generators More Ways to Join Strings Nonstandard String Literals Raw Strings Semantic Version Strings Byte Array Literals String Searching and Replacing String Interpolation Additional Collection Types Dictionaries Sets Structs Named Tuples Initializing Arrays with Functions The repeat() Function The fill() Function Mutability with the fill() and repeat() Functions The zeros() and ones() Functions The reshape() Function Array Manipulations Useful in Numerical Algorithms General Concatenation Logical Indexing Adjoints and Transposes Matrix Multiplication Enumeration and Zipping The enumerate() Function The pairs() Function The zip() Function Conclusion 6 FUNCTIONS, METAPROGRAMMING, AND ERRORS
📄 Page
15
Functions and Their Arguments Concise Syntax for Keyword Arguments The Splat and Slurp Operators Destructuring Operators Are Functions Too The Mapping, Filtering, and Reduction Operators do Blocks Symbols and Metaprogramming Expression Objects Expression Object Interpolation Macros How to Create Macros Useful Macros Error Handling Types of Errors The Call Stack try...catch Blocks Using throw() The finally Clause Conclusion 7 DIAGRAMS AND ANIMATIONS Diagramming with Luxor The Graphs Package The Adjacency Matrix Factor Trees Animations with Javis Closures Epicycle Animation Animations with Reel Interactive Visualizations in Pluto Conclusion
📄 Page
16
8 THE TYPE SYSTEM Types in Practice “Big” and Irrational Types Type Promotion Collections The Type Hierarchy Type Assertions and Declarations Functions and Methods: Multiple Dispatch Creating Multiple Methods Extending Built-in Functions with New Methods Understanding Union Types and the <: Operator User-Defined Types Creating Abstract Types Creating Composite Types Using Composite Types Defining structs with Base.@kwdef Performance Tips Vanquish Type Instability Avoid Changing the Types of Variables Type Aliases Parametric Types Plot Recipes The Plotting Pipeline The Series Recipe The Plot Recipe Type Recipes User Recipes The @userplot Macro Conclusion PART II
📄 Page
17
APPLICATIONS 9 PHYSICS Bringing Physical Units into the Computer with Unitful Using Unitful Types Stripping and Converting Units Typesetting Units Plotting with Units Making Plots for Publication Error Propagation with Measurements Fluid Dynamics with Oceananigans The Physical System The Grid The Boundary Conditions The Diffusivities The Equation of State The Model and Initial Conditions The Simulation The Results Solving Differential Equations with DifferentialEquations Defining the Physics Problem and Its Differential Equation Setting Up the Problem Solving the Equation System Examining the Solutions Defining Time-Dependent Parameters Parametric Instability Combining DifferentialEquations with Measurements Conclusion 10 STATISTICS Probability
📄 Page
18
Random Numbers in Julia The Monty Hall Problem Counting Factorials Binomial Coefficients Modeling a Pandemic Common Statistics Functions Distributions The Normal Distribution Probability Density Functions Dealing with Data Missing Values CSV Files Dataframes Multivariate Data Other Packages JuliaDB for Out of Core Datasets RCall for Interacting with R P-hacking Conclusion 11 BIOLOGY The Julia Biology Ecosystem Simulating Evolution with Agent-Based Modeling Overview of the Simulation Problem The Predator and Prey Agents Constants Defining Model Behavior Utility Functions Model Initialization Functions to Extract Information from the Model Stepping Through the Simulation Running the Simulation
📄 Page
19
Visualizing System Behavior Analyzing the Results Conclusion 12 MATHEMATICS Symbolic Mathematics Numerical-Symbolic Modeling with Symbolics Math Manipulation with SymPy and Pluto Linear Algebra Views Linear Algebra Examples The LinearAlgebra Package Specialized Matrix Types Equation Solving and factorize() Conclusion 13 SCIENTIFIC MACHINE LEARNING Automatic Differentiation in a Physics Problem Differentiating with ForwardDiff Calculating Forces from Potentials Probabilistic Programming Testing for Fairness of a Coin Inferring Model Parameters from Series Observations Conclusion 14 SIGNAL AND IMAGE PROCESSING Signals in Time Exploring a Sound Sample Analyzing Frequencies
📄 Page
20
Filtering Image Processing Loading and Converting Images Counting Cells Using an Area Fraction Counting Cells by Recognizing Features Applying Advanced Array Concepts Conclusion 15 PARALLEL PROCESSING Concurrency Paradigms Multithreading Easy Multithreading with Folds Manual Multithreading with @threads Spawning and Synchronizing Tasks Multiprocessing Easy Multiprocessing with pmap Networking with Machine Files Going Manual with @spawnat Multiprocessing Threads with @distributed Summary of Concurrency in Julia Conclusion INDEX