national laboratory - iopscience · change solvers and analyze the results, makes running multiple...

32
This content has been downloaded from IOPscience. Please scroll down to see the full text. Download details: IP Address: 54.39.106.173 This content was downloaded on 03/09/2020 at 02:44 Please note that terms and conditions apply. You may also be interested in: Multiphysics simulations of nanoarchitectures and analysis of germanium core-shell anode nanostructure for lithium-ion energy storage applications T Clancy and J F Rohan Multidimensional, multiphysics simulations of core—collapse supernovae O E B Messer, S W Bruenn, J M Blondin et al. A software platform for the analysis of dermatology images Maria Vlassi, Vlasios Mavraganis and Panteleimon Asvestas Multi-scale data visualization for computational astrophysics and climate dynamics at Oak Ridge National Laboratory Sean Ahern, Jamison R Daniel, Jinzhu Gao et al. Special issue: multiphysics modeling, simulation and experiments in micro and nanosystems Alberto Corigliano, Michel Lenczner and Véronique Rochus An alternative method to optimise the SLW Grey Gases P Evrard, V Feldheim and P Lybaert Towards gravitational-wave astronomy of core-collapse supernova explosion Kei Kotake Prediction of the Lorentz Force Detuning and pressure sensitivity for a Pillbox cavity M. Parise Rapid structural analysis of nanomaterials in aqueous solutions Sou Ryuzaki, Makusu Tsutsui, Yuhui He et al.

Upload: others

Post on 17-Jul-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

This content has been downloaded from IOPscience. Please scroll down to see the full text.

Download details:

IP Address: 54.39.106.173

This content was downloaded on 03/09/2020 at 02:44

Please note that terms and conditions apply.

You may also be interested in:

Multiphysics simulations of nanoarchitectures and analysis of germanium core-shell anode

nanostructure for lithium-ion energy storage applications

T Clancy and J F Rohan

Multidimensional, multiphysics simulations of core—collapse supernovae

O E B Messer, S W Bruenn, J M Blondin et al.

A software platform for the analysis of dermatology images

Maria Vlassi, Vlasios Mavraganis and Panteleimon Asvestas

Multi-scale data visualization for computational astrophysics and climate dynamics at Oak Ridge

National Laboratory

Sean Ahern, Jamison R Daniel, Jinzhu Gao et al.

Special issue: multiphysics modeling, simulation and experiments in micro and nanosystems

Alberto Corigliano, Michel Lenczner and Véronique Rochus

An alternative method to optimise the SLW Grey Gases

P Evrard, V Feldheim and P Lybaert

Towards gravitational-wave astronomy of core-collapse supernova explosion

Kei Kotake

Prediction of the Lorentz Force Detuning and pressure sensitivity for a Pillbox cavity

M. Parise

Rapid structural analysis of nanomaterials in aqueous solutions

Sou Ryuzaki, Makusu Tsutsui, Yuhui He et al.

Page 2: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

Astrophysical RecipesThe art of AMUSE

Simon Portegies Zwart and Steve McMillan

Chapter 1

What is Computational Astrophysics?

Informatica gaat net zo min over computers als astronomie over telescopen.Informatics is as little about computers as astronomy is about telescopes.

Edsger W. Dijkstra

Computational astrophysics has come a long way since the early days whenastronomers began to use support devices for their calculations. In this chapter, wereview some key developments in this field, embrace the relatively new concepts ofmultiscale and multiphysics simulations, and introduce the Python programmingenvironment that we will use for the rest of this book. We do this by presenting a seriesof examples that may look arcane now, but will (we hope) become clearer as weprogress through the text.

1.1 Computational AstrophysicsComputational astrophysics bridges observation and theory. The improved qualityof observations and the need for deeper understanding of the underlying physics hasdriven demand for higher resolution and increased physical realism in numericalsimulations. With exponentially growing hardware performance, we expect that theimportance of large-scale simulations will only increase, so the software must alsoimprove to keep pace with both observations and theory.

1.1.1 Origin of This Book

The idea for this book originated from writing the first version of the AstrophysicalMUltipurpose Software Environment (AMUSE) in 2009, which at the time wecalled the MUltiphysics Software Environment (MUSE; Portegies Zwart et al.2009). Since then, we have taught numerous courses in computational astrophysicsbased on our software, and supervised many students in research projects based on

doi:10.1088/978-0-7503-1320-9ch1 1-1 ª IOP Publishing Ltd 2018

Page 3: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

AMUSE. The notes from these lectures and the example scripts written by ourstudents and ourselves formed the first version of what we called the AMUSEPrimer. Later, that idea gelled into a book, which you are reading right now.

Writing this book was fun. Writing the software was even more fun. Writing theexample scripts was the hardest thing to do. The simplest-looking codes often causedus the most work. Our objective was to make these codes as short and crisp aspossible. Making scripts educational without losing their main purpose was ourprimary challenge.

1.1.2 Hands-on is Hands-on

In our experience, the best way to learn is by doing—and the best way to start doingis to take an example that resembles your objective to some degree, and build on it.We therefore include a large number of examples in a separate repository within theAMUSE code distribution, with many code snippets incorporated into this book.

In practice, we prefer to work as follows:• start with a scientific question;• identify the minimal physics needed to address the question;• find an example script that resembles the target problem as closely as possible;• rewrite that script to make it solve our problem.

Making figures and animations can be time-consuming but also very rewarding.Making a publishable figure can take as much as a day. In our examples, we adoptpyplot1 from the matplotlib package (Hunter 2007) as our graphics library.There are many alternatives to matplotlib for making animations or figures, butits principal advantage is its transparent interface with Python, which makes it easyto incorporate into AMUSE.

A simple script can be written in a few hours; a more complicated script may takedays to get right. However, that is only the beginning of the long, painstakingprocess from test script to production code. This generally entails a number ofstages, as illustrated in Figure 1.1. The main steps include adjusting the script toone’s needs, then refactoring the script, followed by profiling and optimization. Weinclude the refactor step to stress the importance of preserving readability of sourcecode, which so often leads to reproducible results (see Beck & Andres 2004, for moreabout refactoring).

1.1.3 What about the Math?

As Albert Einstein wrote on 1943 January 7, to nine-year-old Barbara Lee Wilson:

Do not worry about your difficulties in Mathematics. I can assure you mineare still greater.

1pyplot is well-documented and publicly available as open source from http://matplotlib.org/api/pyplot_api.html.

Astrophysical Recipes

1-2

Page 4: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

A solid background in math is nice, and surely helpful, but you can probably readand understand most of this book with only rudimentary mathematics and calculus.Similarly, a PhD or other strong background in astrophysics or computer sciencewill certainly make some of the material easier to digest, but we have successfullyused AMUSE and this text with students at all levels, from freshman undergraduateto Masterʼs to PhD.

1.1.4 Objective of This Book

This book is about how to perform simulations of astrophysical phenomena. Thesesimulations have the goal of mimicking nature, or at least certain aspects of it, inorder to better understand the universe. By the end of this book, you will be able toperform many high-end simulations yourself. You will have learned how to set upinitial conditions, how to design and develop a simulation environment to addressyour astrophysical question, how to perform the runs, and how to analyze theresulting data.

You can read this book in several ways. You can simply start at the beginning andwork through to the end, or you may prefer to pick out the pieces you need in orderto bootstrap your own research project. Either way, we recommend that you readthe first couple of chapters, to understand how AMUSE works and some of its basicprogramming ideas.

1.1.5 What is Missing from This Book

This book is far from exhaustive. Many topics, such as data mining, high-perform-ance and distributed computing, programming paradigms for graphics processing

Figure 1.1. Workflow for designing a production script.

Astrophysical Recipes

1-3

Page 5: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

units, operating systems, and the effects of limited numerical precision are entirelyseparate disciplines, so we can only refer you to other resources. AMUSE containsfar more functionality than we can describe. We will only briefly address thealgorithms underlying many of the phenomena discussed. Our discussion of theunderlying physics is also necessarily limited. This is not an astrophysics text—rather, our goal is to present just enough astrophysics to allow you to harness themodules we describe.

Of the many astrophysical phenomena we could include, we have decided to limitour scope to gravitational dynamics, stellar evolution, hydrodynamics, and radiativetransport. We neglect a lot of physics, including asteroseismology, astrobiology,planetary geology, cosmology, and tidal dissipative effects. These are not unim-portant, but the book is finite and new modules addressing such areas are constantlybeing added to the AMUSE framework.

1.1.6 Outline of the Book

In these first few chapters, we discuss scripts designed to address single physicalprocesses, for which only one numerical solver is required. A minimal solver is thesimplest possible script needed to run a particular solver. In AMUSE, the low-levelsolvers—usually written in high-performance languages and often optimized forparallel architectures—are called community codes. When we include the AMUSEPython interface structure, we generally use the more generic term communitymodule. In practice, we often need additional modules for generating initialconditions, boundary values, or post-production analysis, but the main work in aminimal code is performed by a single community module. Minimal solvers run aparticular code and stop after producing just enough information to gauge thequality of the solution. The solvers presented here should be viewed as examples toillustrate the AMUSE programming style and module interfaces, but they can alsobe used as a basis for more advanced work.

The next level of complexity is a simple solver, which is an extended version of aminimal solver. Simple solvers are meant to illustrate more complex and practicalmonophysics applications. Within the AMUSE framework, we can run a single codeas a standalone program. AMUSE contains multiple solvers for each physical domainit addresses, which allows for detailed and instructive comparison between them. Theease with which initial conditions can be generated, and with which the user canchange solvers and analyze the results, makes running multiple solvers on the sameproblem a useful exercise. In this regard, the main advantage of using AMUSE is theunified way in which the input is parsed and delivered to—and results are returnedfrom—the solver. This makes it possible to use exactly the same initial conditions foreach of a set of numerical solvers and analyze the resulting data in a uniform way.

We begin our explanation of AMUSE fundamentals using simple solvers ingravitational dynamics (Chapter 2) and stellar evolution (Chapter 3). In Chapter 4,we discuss how these codes can be coupled to create a simple multiphysics solver. InChapters 5 and 6, we expand our scope to include more elaborate physics modulesaddressing hydrodynamics and radiative transport. In the final two chapters, we

Astrophysical Recipes

1-4

Page 6: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

focus on what might actually be called the main topic of the book, namely how tocouple multiple codes into a homogeneous multiscale and multiphysics solver. Wehave adopted this presentation order for its steady increase in physical complexityand its systematic introduction of more and more sophisticated AMUSEcapabilities.

1.2 A Brief History of Simulations in AstrophysicsThe first recordings of theoretical astronomy date back to the Egyptian 18thdynastic (1550–1292 BC) calculations by Pharaoh Hatshepsut’s architect, Senmut;portions of the murals found in his tomb at Deir el-Bahri can be found at http://www.metmuseum.org (Dorman 2006, pp. 107–109). Figure 1.2 presents part of thismural. Such calculations enabled astronomers to recognize structure and describepatterns in the heavens, an aspect of astronomy that is still relevant today.

Modern astronomy started with the discovery of the first refracting telescope,built by Hans Lippershey in 1608, which had a collecting area of about 1 cm2.Galileo Galilei reported the first astronomical applications in 1609, using a telescopeof similar design. In the 400 years since that momentous first application of newtechnology, the collecting areas of the largest research telescopes have increased by afactor of about 106, becoming the 10 m class telescopes in widespread use today.

Digital computers were introduced in the late 1930s (Zuse 1967, 1993). In 1945,the first commercial programmable model, ENIAC, achieved a computational speed

Figure 1.2. Reproduction of the lower part of the second tomb of Senenmut’s stela, dated around 1479–1458B.C. (accession number MMT:48.105.52 (TT353), Figure 27 of Wilkinson 1979, GNUGeneral Public License,Rogers Fund, 1948). This unique mural shows, apart from all the Egyptian gods, the most importantconstellations and a much-debated conjunction between the Sun and the Pleiades star cluster. The originalphotograph was presented in Dorman (1991; Dorman 2006, pp. 107–109).

Astrophysical Recipes

1-5

Page 7: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

equivalent to about 200 modern floating point (double precision) operations persecond (flops). (We say “equivalent” because ENIAC was essentially a singleprecision machine.) Today, the fastest supercomputers achieve speeds exceeding1017 flops, a speedup of a factor of roughly 1015 in raw performance in just sevendecades. Thus, while observing technology has grown impressively—but relativelyslowly—over the past four centuries, computer scientists have witnessed a techno-logical explosion in living memory.

The ongoing revolution in the availability of digital computers has led to anentirely new branch of research, in which key facilities are not confined to highmountain tops in Hawaii or the Chilean Andes; they are more often found in theroom next door. Astronomers quickly realized that they could use computers toarchive, process, analyze, and mine the copious amounts of data taken by observingcampaigns. However, arguably the greatetst impact on the way astronomers pursuetheir scientific questions has been made by numerical simulations of astrophysicalphenomena.

Astronomical research lends itself naturally to computation because it ischaracterized by large ranges in temporal and spatial scales, complex and couplednonlinear processes, and the extreme conditions found in interstellar space. With theappearance of digital computers, it became possible to study processes in theintergalactic vacuum, hot plasmas at stellar surfaces, billion-year timescale proc-esses, and black-hole physics, none of which can be studied in Earth-basedlaboratories. The current major limitation to studying the universe by means ofcomputation lies in software, particularly with regard to our limited understandingof algorithms that can solve multiscale, multiphysics problems. AMUSE is anattempt to address these issues.

1.2.1 The First Simulation Experiments

One of the first astrophysical simulations was carried out in 1941 by Erik Holmberg,a graduate student at Lund University who had access to a number of photocells.Based on the fact that the intensity of radiation drops off as the inverse square of thedistance, like the force of gravity, he devised an experiment to simulate two collidinggalaxies. The initial setup for a single “galaxy” in Holmberg’s experiment ispresented in Figure 1.3. The progress of his experiment is shown in Figure 1.4.The arrows indicate the directions in which the galaxies move with respect to oneanother, and how they rotate. This experiment made Holmberg one of the foundersof what is now an immense body of astronomical research in gravitational dynamics,some of it reviewed by Binney & Tremaine (1987).

Holmberg had no access to a computer, so all of his calculations were performedby hand. His article (Holmberg 1941) is interesting in many respects, but unclear onexactly how the forces (photon counts in his case) were used to update the positionsof the particles (the light bulbs). Today, in a comparable paper, we might state thatthe integration was performed using (say) a fourth-order Hermite predictor–corrector scheme with direct force evaluation and zero softening (see Makino &Aarseth 1992). The choice of algorithm (in this case the Hermite scheme) is an

Astrophysical Recipes

1-6

Page 8: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

important part of the solution. Although this level of detail might sound excessive,you will better appreciate such considerations by the time you have read Chapter 2.

1.3 Software Used in This Book1.3.1 Motivation for a Homogeneous Software Environment

Developing high-quality simulation software is relatively straightforward when thephysical scope of the problem is limited. The task becomes considerably moredifficult once the application spans multiple physical domains, or if the dynamicrange in temporal or spatial scales exceeds the precision of the hardware. Successful

Figure 1.3. Copy of Figure 3 from Holmberg (1941), presenting the initial conditions for a single galaxy inHolmberg’s simulation of two colliding galaxies. (Copyright AAS. Reproduced with permission fromHolmberg 1941.)

Figure 1.4. Copy of Figure 4(a) from Holmberg (1941), presenting two snapshots of the results from hiscalculations. Both snapshots were taken at the moment the two galaxies were separated by twice their radii,one before the interaction (left) and one after the first close approach (right). (Copyright AAS. Reproducedwith permission from Holmberg 1941.)

Astrophysical Recipes

1-7

Page 9: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

examples of complex multiphysics software in computational astrophysics areNBODY7 (Aarseth 1999, 2011), FLASH (Fryxell et al. 2000, 2010), and GADGET(Springel et al. 2001; Springel 2000), all of which have broad user bases and can beapplied to a wide variety of problems. (Note that, where possible, we provide tworeferences for each software implementation: one to the publication in which thepackage was first described, and another to the Astrophysics Source Code Library athttp://ascl.net/.) Some of these codes address relatively narrow ranges of physics andare limited by the specific numerical algorithms adopted to solve the underlyingequations, but others, like FLASH, are highly modular in their internal organization—in some ways similar to AMUSE.

Figure 1.5 presents typical temporal and spatial scales for a number ofastronomical phenomena. The ellipses indicate specific areas of interest. The colorsindicate physical domains: gravity (blue), stellar evolution (red), hydrodynamics(yellow), and radiative processes (green). Several domains are identified by name,such as the collapse of a giant molecular cloud (top right, in yellow), and the range ofhabitable planet orbits (blue circle at lower left). Gravity and hydrodynamics span abroad range of temporal and spatial scales, whereas radiative processes and stellarevolution exhibit much narrower ranges. Note that both spatial and temporal scales

Figure 1.5. A number of typical scales, for gravitational dynamics (blue), stellar evolution (red), hydro-dynamics (yellow), and radiative transfer (green), are indicated at several locations in the plane of temporaland spatial scales. Here, several small scales (mergers indicated by M) and common envelope evolution(indicated by CE) are embedded within the orbital dynamics scale ellipse.

Astrophysical Recipes

1-8

Page 10: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

span a range of about 14 orders of magnitude, from galactic orbits at one extreme tostellar mergers or intricate orbital dynamics at the other.

Many existing simulation codes provide excellent solvers within their specificphysical domains, but astrophysical problems often require solvers for a wide varietyof domains. For example, understanding the ejection of primordial gas from anembedded star cluster born during a galaxy merger requires simultaneous treatmentsof collisional stellar dynamics (the protostellar cluster), collisionless stellar dynamics(the galaxy merger), hydrodynamics (interstellar gas), stellar evolution (embeddedprotostars and stars), and radiative processes (feedback between stars and theinterstellar gas). All these processes occur on comparable temporal and spatial scales.

Instead of designing new algorithms to solve all of these problems simultaneously,we adopt the philosophy that each of the physical domains can be solved separately,then combined into a consistent solution at discrete intervals in time and space.Validation of such a simulation could subsequently be accomplished by recomputingthe model with a different solver for each of the physical domains. In this way, wecan study the convergence (or the absence thereof) of the solution with a sequenceof numerical implementations. The Astrophysical Multipurpose SoftwareEnvironment (AMUSE; Portegies Zwart 2011; Portegies Zwart et al. 2013) allowsa user to combine existing solvers to build new applications that can then berecombined to study increasingly complex problems. This enables the growth ofmultiphysics and multiscale application software in a hierarchical fashion, andallows testing of each intermediate step as the complexity of the software increases.

AMUSE has a hierarchical component architecture that encapsulates dynam-ically shared libraries for simulating stellar evolution, gravitational dynamics,(magneto)hydrodynamics, and radiative processes; it also has limited support forastrochemistry. Applications are able to use some or all of these resourcessimultaneously, and can exchange data in a unique and deterministic way. Withthis hybrid simulation environment, it becomes possible to study multiphysicsprocesses operating on a broad range of length and timescales.

1.3.2 Choice of Programming Languages

We have adopted Python (van Rossum 1995a, 1995b, 1995c, 1995d) as theimplementation language for the AMUSE framework and high-level managementfunctions, including bindings to the communication interface. This choice ismotivated by Python’s flexibility, broad acceptance in the scientific community,object-oriented design, and ability to allow rapid prototyping, which shortens thesoftware development cycle and enables easy access to the community code in thecommunity module (albeit at the cost of slightly reduced performance). However,the entire AMUSE framework is organized in such a way that relatively littlecomputer time is actually spent in the framework itself—most time is (or should be)spent in the community code(s). The overhead from Python compared to a compiledhigh-level language is typically ≲10%, and often much less (Pelupessy et al. 2013).

As discussed further in Appendix A.1.1.2, our implementation of the communi-cation layer in AMUSE uses the standard Message Passing Interface protocol (MPI;

Astrophysical Recipes

1-9

Page 11: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

Gropp et al. 1996) and SmartSockets (Maassen & Bal 2007). Normally, MPI andSmartSockets are used for communication between compute nodes on paralleldistributed-memory systems or within computational grids. In AMUSE, however,they are used as communication channels between all processes, whether or not theyreside on the same node as the control script and/or are themselves parallel.

AMUSE community codes are written in a variety of languages, reflecting theprogramming backgrounds and preferences of their authors. As a result, there aretwo interface functions for each community code. The one on the AMUSE side iswritten in Python and is called the proxy. The interface on the community code sideis called the partner and is written in the native language of that code. These twointerfaces communicate via one of the message-passing protocols just described.Thus, our only real restriction on supported languages is the requirement that thecommunity code is written in a language with MPI or Smart Sockets bindings, suchas C (Ritchie 1993b, pp. 201–208; Ritchie 1993a), C++ (Stroustrup 2013), Java(Gosling et al. 1996, 2014), and members of the FORTRAN family (Backus 1981).

We emphasize that, from the user perspective, the details of the interface andcommunication protocols are invisible. These details are central to the AMUSEdesign, but most high-level users are blissfully unaware of them. To the user, aPython AMUSE script looks just like a traditional serial program.

1.3.3 Design of AMUSE

The AMUSE project goal stipulates three basic functionalities:(1) a homogeneous, physically motivated interface for existing astronomical

simulation codes;(2) the incorporation of multiple community codes from four fundamental

domains (stellar evolution, gravitational dynamics, hydrodynamics, andradiative transfer); and

(3) the ability to design new simulation experiments by combining one or moreof the community codes in various ways.

In this way, researchers can concentrate on physically relevant details, such as thecalling sequence for the various physical domains, without having to worry aboutthe many technical details.

Each of the existing community codes in AMUSE is embedded in an interfacelayer that realizes communication between the AMUSE framework and a com-munity code. One important advantage of this strict separation is that it explicitlyprohibits short-cut communication between independent subroutines, greatly dimin-ishing the opportunities to create “spaghetti code.” In addition, it allows us tomanipulate data as it moves between the community code and the framework. Onesuch data manipulation is the conversion of units, as discussed in Section 1.4.2.Parameters that depend on community code are largely managed by the framework,as are the acquisition and mining of simulation data. Figure 1.6 illustrates schemati-cally the philosophy of AMUSE, with the central AMUSE framework surroundedby its four fundamental physical solvers.

Astrophysical Recipes

1-10

Page 12: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

New hybrid codes can be written in AMUSE by combining community codesusing Python. An AMUSE Python script for solving a particular problem prescribesthe order in which events are handled and specifies the numerical solver that shouldbe used to resolve each event. Once initial conditions are generated and thesimulation is completed, the resulting data can be stored or further analyzed usingthe tools available in AMUSE, or developed by the user. AMUSE entirely handlesthe technical problems associated with coupling codes, setting boundary conditions,specifying run-time parameters, and guaranteeing that the various elements com-municate in the proper units. A thorough understanding of the limitations of each ofthe incorporated codes is important for assessing the quality of the simulation, butthe burden of managing the technical details is not forced on the user.

We have demonstrated the modularity and interchangeability of the AMUSEcommunity codes for solving the basic physical processes described above. The usercan select from a variety of gravitational N-body solvers (symplectic N-body codes,direct N-body codes, and tree codes) by changing a single word in the script. Thesame holds for stellar evolution codes (parameterized and Henyey codes), hydro-dynamics solvers (smooth particle hydrodynamics and adaptive mesh refinementcodes), and radiative transfer codes (Monte Carlo photon transport codes, andtessellated photon flow solvers). The modularity, and how a complex cascade of

Figure 1.6. Multiscale and multiphysics codes are connected disciplines, as depicted here in the domain-application plane.

Astrophysical Recipes

1-11

Page 13: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

numerical solvers can grow to an end product, is illustrated in Chapter 8. Thiscascade of jargon may sound like Jabberwocky (Carroll 1871) right now, but wehope that much of it will eventually make sense by the time you reach the end of thisbook.

1.3.4 Terminology

The basic structure of the AMUSE framework is illustrated in Figure 1.7. The figureis subdivided into three general parts. The top layer (red and orange) is mostly user-written, the middle layer (blue) implements the interfaces onto the community codes,and the bottom layer (cyan) consists of the community modules and the actualcommunity source code, which is connected to the rest of the framework via the MPIor sockets.

The components can be described as follows:• The Python user script (marked red in Figure 1.7), which addresses a specificphysical problem or set of problems, in the form of system-provided or user-

Figure 1.7. General structure of the AMUSE framework. The user writes the Python script (top red layer). Thelower orange layers are responsible for units and data structures. The framework outlined in blue representsthe interfaces to the community modules (blue for gravitational dynamics, red for stellar evolution, yellow forhydrodynamics, and radiative transfer in green, to conform with the color coding of Figure 1.5), which connectvia sockets or MPI (cyan) to the community codes at bottom. Information flows downward to the communitymodules, as indicated by the red arrows, as well as upward, back to the Python script.

Astrophysical Recipes

1-12

Page 14: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

written Python commands that serve as the user interface onto the frame-work. This is the only part of a production script that needs to be written bythe user. The coupling between community codes is implemented in this layer,with the help of support classes for converting units and data structuresprovided by AMUSE.

• The community module, comprising three key elements:The manager (orange), which provides an object-oriented interface ontothe communication layer via a suite of system-provided utility functions.This layer handles unit conversion. It also contains the state engine andthe associated data repository, all of which are required to guaranteeconsistency of data across modules. This layer is generic—it is not specificto any particular problem or physical domain.The communication layer (blue), which realizes the bidirectional commu-nication between the manager and the community code layer. This isimplemented via a proxy and an associated partner, which togetherprovide the connection to each community code.The community code layer (cyan), which contains the actual communitycodes and implements control and data management operations on them.Each piece of code in this layer is domain-specific, although the code maybe designed to be very general within its particular physical domain.

1.3.5 Installing AMUSE

Before you continue reading, we advise you to turn to Appendix A (Section A.2 inparticular) and install AMUSE (or the binary release from amusecode.org). Here,we give only a brief overview of the installation steps. We assume that you areworking in a Linux or MacOSX environment. We don’t recommend or supportAMUSE under Windows, except within a Linux environment such as Cygwyn (seehttps://www.cygwin.com/). Throughout this book, we will use the (bash/make)syntax that ${AMUSE_DIR} refers to the base directory in which the AMUSE codebase is installed.

• To download AMUSE, go to https://github.com/amusecode/amuse/ and press“Clone or download.” This will download a file amuse-master.zip.

• Move the file amuse-master.zip to some local directory /home/me/amuse and unzip it. It will create the subdirectory amuse-master.

• Follow the instructions on the github page, starting at “Compilers,” or turnto Section A.2. Be sure to read the guidance about exporting FC and F77, inorder for the build to succeed.

• Install the prerequisite software (see Section A.2.2). Instructions on how to dothis are on the github page. Note that Part 2b on https://github.com/amusecode/amuse/ is essential to make AMUSE work properly on yoursystem; configuring the build process using ./configure will fail otherwise.

• Set your local environment variables and follow the build instructions. Somemodules may not compile, which is perfectly normal—some require specialhardware (such as a dedicated graphics card, unusual compilers, or non-

Astrophysical Recipes

1-13

Page 15: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

standard libraries). Some codes may even be absent: MESA, for example,must be downloaded separately.

• Install matplotlib, a Python-based plotting package that is vital for manyof our examples. Sometimes, matplotlib can be hard to install via a Linux-like package manager, such as

%> apt-get install python-matplotlib

In that case, it may be easier to install matplotlib from source. Forinstructions, see https://matplotlib.org/users/installing.html.

• Run a standard set of tests in the directory ${AMUSE_DIR}/test. In the testdirectory, you may want to go to one of the subdirectories, such as nosetestcodes_tests, core_tests, ext_tests or ticket_tests, and run

%> nosetest *

This may result in a few warnings, mainly due to round-off, but hopefully notany errors.

• Run some of the examples from the book. A simple bash script to runAMUSE applications, called amuse.sh, is located in the directory in whichyou installed the package. Just say

/home/me/amuse/amuse.sh amuse_script.py

Here, we assume that you have installed AMUSE in the directory /home/me. Alternatively, you may want to invoke AMUSE directly from your ownPython or iPython kernel (Perez & Granger 2007), which is possible if youexport the appropriate directories where you installed AMUSE:

export AMUSE_DIR=/home/me/amuse

export PYTHONPATH=${PYTHONPATH}:/home/me/amuse/test:/home/me/amuse/src

You may want to add these lines to the .bashrc file in your root directory.Once this is done, you can just say

python amuse_script.py

Your AMUSE download comes with all of the example, data, and figure filesused in this book. They can be found in the subdirectory examples/textbook/of your AMUSE installation directory. You may want to run your first AMUSEexample script by typing on the command line

%> python /home/me/amuse/examples/textbook/Sun_venus_earth.py

(Here again, we assume that your AMUSE installation is located in directory/home/me/amuse/.) This should produce a figure that looks similar to Figure 1.8below.

Astrophysical Recipes

1-14

Page 16: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

1.3.6 Running AMUSE

By now, you should have built and tested AMUSE, as described in Appendix A (seeSection A.2 in particular), and are probably wondering “What can AMUSE do forme?” This section will get you started. If youʼre new to Python, youʼll find theofficial Python documentation2 a valuable resource. Note that AMUSE wasdeveloped with Python 2.7 in mind, and we still recommend use of this version.However, it is also fully functional with Python 3 (see https://www.python.org/).

You can run AMUSE interactively using the command line

%> /home/me/amuse/amuse.sh

or if your environment is already set up properly (see Section A.2.8), you can simplywrite

%> python

Either way, once Python has started, you can load AMUSE via

>>> from amuse.lab import *

This line is a lazy (but very convenient) way to import the entire AMUSE package ina single call. We generally do not advise it, because it pollutes the Python namespace. Rather, we recommend that, wherever possible, individual packages beimported from amuse.lab by name. Still, in many examples below and in laterchapters, we are unable to resist the simplicity of importing the entire package.Throughout this manuscript, we will present source code in this way, and willassume that the appropriate AMUSE libraries have been loaded.

The listings presented here and elsewhere in the book are designed to be cut andpasted into your Python interpreter or your local file editor. Complete source codefor running any of the simulations and for generating all figures in this book areavailable in the directory ${AMUSE_DIR}/examples/textbook (assuming it wasproperly installed).3 We hope that these snippets and listings encourage you toexperiment and initiate interesting research projects.

Unfortunately, we have found that many PDF readers have difficulties preservingindentation after cutting and pasting—a serious problem for a language whereindentation is key! In that case, we recommend pasting into an editor and manuallyadding the indentation there, or simply using the code contained in ${AMUSE_DIR}/examples/textbook. You should be able to cut and paste the source codereferences given in many figure and listing captions directly into a terminal window

2https://docs.python.org/2.73 Examples are also online at https://github.com/amusecode/amuse/tree/master/examples/textbook.

Astrophysical Recipes

1-15

Page 17: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

and expect them to run (again assuming that AMUSE_DIR has been properlydefined).

1.4 Initial ConditionsEvery simulation in AMUSE requires initial conditions to start the calculation.Typically, these entail choosing dynamical quantities (such as particle masses,positions, and velocities), stellar properties (such as radii and luminosities), or gasproperties (such as density, temperature, and composition). These quantities areoften the result of some prior calculation, or they may represent a restart from apreviously stored state. In principle, any mathematically consistent set of initialchoices is a valid way to start a simulation. In practice, however, we generally wantto use some reasonable, physically motivated starting point for further study.

Some initial conditions are realistic and others are not. Realistic initial conditionsare the goal of (almost) all researchers, but they are hard to find and generally evenharder to explain. Most studies start with somewhat unrealistic initial conditions,with the expectation (or at least, the hope) that they capture the fundamental physicsnecessary to study the desired phenomenon, and that the details of the simulationwill rapidly drive the system into some physically more meaningful configuration. Infollow-up studies, we can then improve on the earlier choice of initial conditions, sayby covering a larger part of parameter space or by zooming in on a region of interest.In some cases, such as core collapse in an idealized equal-mass star cluster (seeSection 2.1.3.2), the evolution is quite insensitive to the details of the initialconditions. In others, however, such as star formation in an interstellar molecularcloud (Chapter 5), the outcome depends crucially on the initial state.

A simple example of unrealistic but widely accepted initial conditions are thoseused in gravitational N-body simulations of star clusters. Such simulations generallystart by setting the number of stars N, and distributing them in space with specifiedradial (spherically symmetric) density and velocity profiles. Most modern studies ofstar clusters incorporate some sort of (parameterized) stellar evolution, so the initialconditions must then also include stellar masses and radii. The entire system is thenscaled (usually by adjusting the velocities) to virial equilibrium (see Section 2.1.2)before high-precision N-body integrators are used to study the dynamical evolutionof the system. From an astronomical point of view, these initial conditions are notcorrect, but they can still be very useful in the study of gravitational dynamics.

More realistic initial conditions for this problem might start with an interstellargas cloud that collapses and fragments to form stars. Once massive stars begin toshine, they produce winds and radiation that cause the remaining gas to be blownaway, terminating further star formation and leaving behind a star cluster. In thiscase, no ad hoc specifications of the positions and masses of cluster stars arerequired. Of course, this only shifts the problem back in time, as the initialconditions for the gas simulation now must specify the (clumpy) density distributionand the (turbulent) motion of the cloud. Those “initial conditions” in turn depend onthe large-scale flow of gas in the galaxy, and so on. The fact is that there are no“true” initial conditions for this problem, just convenient milestones in a continuous

Astrophysical Recipes

1-16

Page 18: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

process. Most generally adopted initial conditions have problems, but it is hard to domuch better.

AMUSE contains an extensive (and growing) collection of codes to generateinitial conditions. Very often, one code provides the conditions from which anothercode continues. For example, when two stars collide, a stellar evolution code mightprovide the initial density and temperature profiles for the two colliding stars, whilea gravitational dynamics code provides their relative positions and velocities. In thisway, two codes are used to generate the conditions for starting a third code thatsimulates the hydrodynamics of the collision. In the following subsections, wediscuss some common initial conditions used in astrophysical studies.

1.4.1 Particles and Particle Sets

Before continuing on to some examples, a short digression on Python classes may bein order. If you are already familiar with this material, please move on to the nextsection. For more detail, please consult Appendix C.

In our experience, most of the syntactic and mathematical features of Python(conditionals, loops, arithmetic operations, et cetera—even the rigid use of inden-tation to define program structure) are broadly intelligible to most programmers,regardless of background. However, some more complex data structures may beunfamiliar to readers used to less structured programming languages, such as C orFortran. Accordingly, we pause here to elaborate on this topic in AMUSE, usingsome important data structures as templates.

A Python class is a data structure with a collection of associated functions, ormethods, designed to manipulate the data. A particularly simple AMUSE class is aParticle, which contains only basic particle particle attributes, such as mass,position, velocity, etc., as well as a key that uniquely identifies the particle in theAMUSE system. It has essentially no user-useful methods to do anything with thedata. We can set or access its contents directly, with no constraints on what we add:

from amuse.lab import Particle, unitsp = Particle()p.mass = 1.0p.mass2 = 42|units.MSunp.whatever = "what?"print p

The particle class is not very useful in and of itself, but it forms the basis for avitally important class called a particle set, which is basically an array ofparticle objects, with conventions regarding content and a collection of methodsproviding information on and control over the data. An element of a particleset is expected to have certain attributes, such as mass, position, velocity,radius, and possibly others. The built-in methods assume that these data exist.

We can create a particle set of 10 particles as follows:

from amuse.lab import Particlesparticles = Particles(10)

Astrophysical Recipes

1-17

Page 19: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

We can then set up attributes in various ways:

particles.mass = 1|units.MSun

sets all masses, while

particles[3].mass = 42|units.kg

sets just one. We could also have set the masses (or positions, etc.) in theParticles creation call, with

particles = Particles(10, mass=1|units.MSun)

Some more useful ways of setting particle set attributes are presented below.Once the basic attributes are set, the methods associated with the particle

set provide commonly used functionality. For example,

ke = particles.kinetic_energy()

computes the total kinetic energy of the particle set, while

pe = particles.potential_energy(G=units.G)

computes the total potential energy. Similarly,

com = particles.center_of_mass()

calculates the center of mass of the particle set, while

particles.scale_to_standard()

places the set in the center of mass frame and scales it to a standard configuration(see Section 2.1.2.1). Many AMUSE functions take a particle set as input and returnanalytical information on it.

You can ask Python to list the methods associated with a class by using the dirfunction:

dir(Particles)

will provide a list of all the methods available in the Particles class. (Note thePython convention that names beginning and ending with double underscores are

Astrophysical Recipes

1-18

Page 20: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

intended for private use, even though you can see them and in principle use themyourself—not recommended!) More extended information can be obtained with

help(Particles)

which provides a detailed description of the methods in the class.Even here, though, Python asserts its inherent flexibility. Unlike classes in more

strongly typed languages, Python classes are customizable. You can add your ownvariables at will for your own purposes—just don’t expect them to be properlymanaged or preserved by the built-in methods!

1.4.2 The Solar System

The initial conditions of the solar system are unknown. However, if we were interestedin the future dynamics of the solar system, we could start with the masses, positions,and velocities of the Sun and eight planets as they are observed at some moment intime, and then integrate the equations of motion forward in time. Table 1.1 presentsinitial conditions from which such a simulation can be started.

Source code to initialize the Sun, Venus, and Earth is presented in Listing 1.1. Itstarts by including two basic AMUSE functionalities—particles and units—definedin the first line of the script:

from amuse.lab import Particles, units

A particle set is then declared in

particles = Particles(3)

Table 1.1. A Realization of the Solar System, up to the Last Known Significant Digit

Name MassPosition Velocity

[MJup] [au] [km s−1]

Sun 1047.517 0.005717 −0.00538 −2.130 × 10−5 0.007893 0.01189 0.0002064Mercury 0.000174 −0.31419 0.14376 0.035135 −30.729 −41.93 −2.659Venus 0.002564 −0.3767 0.60159 0.03930 −29.7725 −18.849 0.795Earth 0.003185 −0.98561 0.0762 −7.847 × 10−5 −2.927 −29.803 −0.000533Mars 0.000338 −1.2895 −0.9199 −0.048494 14.900 −17.721 0.2979Jupiter 1.000000 −4.9829 2.062 −0.10990 −5.158 −11.454 −0.13558Saturn 0.299470 −2.075 8.7812 0.3273 −9.9109 −2.236 −0.2398Uranus 0.045737 −12.0872 −14.1917 0.184214 5.1377 −4.7387 −0.06108Neptune 0.053962 3.1652 29.54882 0.476391 −5.443317 0.61054 −0.144172

Notes. Calculated for 2063 April 5 at 00:00 hours—Julian date 2,474,649.5 days (corresponding to FirstContact Day: http://www.startrek.com/article/origin-of-first-contact-day-explained)—using the Ephemeridesfrom http://ssd.jpl.nasa.gov/txt/p_elem_t2.txt, and estimating the uncertainty in the positions and velocitiesusing the dispersion given by Folkner (2011, pp. 43–48).

Astrophysical Recipes

1-19

Page 21: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

Attribute values are then set. The first particle in the array (particles[0]) isassigned to the Sun and the other two particles to Venus and Earth. (Note the detailsof setting three vector coordinates and units in a single line.) Then, writing

>>> print sun.position

will print out the Cartesian coordinates of the Sun. After initialization, the particlesare moved to the center of mass of the three-body system, using the (class-defined)function move_to_center() mentioned in the previous subsection. At the end ofthe function, the particle set is returned to the main script with

return particles

The integration of the orbits can be carried out using the script in Listing 2.3 (seeSection 2.4.1). Listing 1.2 presents a snippet of code to plot the planets’ positions asthey orbit the Sun. The results of the calculation are shown in Figure 1.8. We usepyplot to present our results, and later will show how to use an AMUSE-tailoredversion for plotting with units and hydrodynamical models. Note that, here andthroughout, we provide references to the scripts that produced the figures; forconvenience, we save the plot in a file (pyplot.savefile(...)) in the currentdirectory and also display it on the screen (pyplot.show()).

from amuse.lab import Particles, units

def sun_venus_and_earth():particles = Particles(3)sun = particles[0]sun.mass = 1.0 | units.MSunsun.radius = 1.0 | units.RSunsun.position = (855251, -804836, -3186) |units.kmsun.velocity = (7.893, 11.894, 0.20642) | (units.m/units.s)

venus = particles[1]venus.mass = 0.0025642 | units.MJupitervenus.radius = 3026.0 | units.kmvenus.position = (-0.3767, 0.60159, 0.03930) | units.AUvenus.velocity = (-29.7725, -18.849, 0.795) | units.kms

earth = particles[2]earth.mass = 1.0 | units.MEarthearth.radius = 1.0 | units.REarthearth.position = (-0.98561, 0.0762, -7.847e-5) | units.AUearth.velocity = (-2.927, -29.803, -0.0005327) | units.kms

particles.move_to_center()return particles

Listing 1.1: Code to generate initial conditions for Venus and Earth orbiting the Sun. Code fragment from${AMUSE_DIR}/examples/textbook/Sun_venus_earth.py.

Astrophysical Recipes

1-20

Page 22: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

1.4.3 The Plummer Sphere

In large systems, initial conditions are not specified exactly, so we must start with arandom realization of a distribution function. In self-gravitating simulations of starclusters, the Plummer (1911) model is often adopted as an initial density profile. InAMUSE, a particle set representing a Plummer sphere of N stars can be generatedwith

bodies = new_plummer_model(N)

The Plummer model represents a self-consistent equilibrium solution to Poisson’sequation, so it is a valid description of an N-body system. However, aside from thefact that it is simple and has no free dimensionless parameters in its description, ithas no special claim to fame as a cluster model. Nevertheless, it is a very commonchoice.

Some initial condition generators are not considered standard, so they cannot beobtained simply by importing the entire AMUSE package via

from amuse.lab import *

These codes have to be imported separately before usage. For example, for “fractal”initial conditions (Goodwin & Whitworth 2004), we must say explicitly

def plot_track(xe,ye,xv,yv, output_filename):

from matplotlib import pyplotfigure = pyplot.figure(figsize=(10, 10))pyplot.rcParams.update({"font.size": 30})plot = figure.add_subplot(1,1,1)ax = pyplot.gca()ax.minorticks_on()ax.locator_params(nbins=3)

x_label = "x [au]"y_label = "y [au]"pyplot.xlabel(x_label)pyplot.ylabel(y_label)

plot.scatter([0.0], [0.0], color="y", lw=8)plot.plot(xe.value_in(units.AU), ye.value_in(units.AU), color = "b")plot.plot(xv.value_in(units.AU), yv.value_in(units.AU), color = "r")plot.set_xlim(-1.3, 1.3)plot.set_ylim(-1.3, 1.3)

save_file = "sun_venus_earth.png"pyplot.savefig(save_file)print "\nSaved figure in file", save_file,"\n"pyplot.show()

Listing 1.2: Plotting the orbits of Venus and Earth around the Sun using pyplot. This tells you more aboutpyplot than about AMUSE, but we present it here for completeness. Code fragment from ${AMUSE_DIR}/examples/textbook/Sun_venus_earth.py.

Astrophysical Recipes

1-21

Page 23: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

from amuse.community.fractalcluster.interface import new_fractal_cluster_modelbodies = new_fractal_cluster_model(N, fractal_dimension = 1.6)

Here, amuse.community.fractalcluster.interface refers to the amuseinterface of the fractalcluster module in the ${AMUSE_DIR}/amuse/src/community subdirectory. This may sound a bit complicated, but type

%> ls /home/me/amuse/src/amuse/community/fractalcluster/

from matplotlib.pyplot import show, xlim, ylim, figurefrom amuse.plot import scatter, xlabel, ylabelfrom amuse.lab import new_plummer_model

def main(N=10):figure(figsize=(5,5))bodies = new_plummer_model(N)scatter(bodies.x, bodies.y)xlim(-1, 1)ylim(-1, 1)xlabel("X")ylabel("Y")show()

Listing 1.3: Routine to plot a Plummer sphere. Code fragment from ${AMUSE_DIR}/examples/text-book/plot_plummer.py.

Figure 1.8. Orbital integration of the Sun, Venus, and Earth for 1 yr using the script in Listing 2.3. The scriptto generate this figure can be found in ${AMUSE_DIR}/examples/textbook/Sun_venus_earth.py.

Astrophysical Recipes

1-22

Page 24: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

which will give you something like

fractal_worker__init__.py interface.f90 interface.py Makefile

fractal_worker.f90_init__.pyc interface.o interface.pyc src

which is the listing of this particular directory. Here, you will find the localMakefile, the src directory that contains the original source code inFORTRAN90, the worker module fractal_worker used by AMUSE, itsFORTRAN source code, and the interface functions interface.xx. The fileinterface.f90 contains the FORTRAN (partner) side of the interface, and thefile interface.py contains the Python (proxy) side (see Figure 1.7).

Figure 1.9 presents a small collection of various initial realizations common inN-body simulations: the Plummer sphere; a King model with structure parameter

Figure 1.9. The inner parts, spanning 1 × 1 Hénon units (Hénon 1971; Heggie & Mathieu 1986, p. 233) ofprojected distributions drawn from: a Plummer model (top left); a King model with W0 = 9 (top right); agalactic disk plus bulge model with Halogen parameters α = 1, β = 5, γ = 0.5 (bottom left); and a cluster withfractal dimension 1.6 (bottom right). Each model is for N = 1000 particles. The source for making the Plummerdistribution is presented in Listing 1.3. The script to generate this figure can be found in ${AMUSE_DIR}/examples/textbook/plot_density_distributions.py.

Astrophysical Recipes

1-23

Page 25: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

W0 = 9 (King 1966); the top view of a galactic disk plus bulge model, for which weadopted Halogen with parameters α = 1, β = 5, γ = 0.5 (Zemp et al. 2008; Zemp2014); and a fractal distribution with fractal dimension 1.6 (Goodwin & Whitworth2004).

The various models are generated with calls similar to those discussed in Section1.4.3. For the King model, we write

bodies = new_king_model(N, W0=9.0)

The Galaxy disk model is constructed with

bodies = new_halogen_model(N, alpha=1.0, beta=5.0, gamma=0.5)

The fractal distribution is generated with

bodies = new_fractal_cluster_model(N=N, fractal_dimension=1.6)

1.4.4 The Initial Mass Function

The default for new_plummer_model and new_fractal_cluster_model isto create stars of equal mass, but usually we want stars to have a range of masses,drawn from some distribution. This distribution is known as the initial massfunction, and is one of the most important quantities in stellar astrophysics.

The initial mass function is often represented as a power law, meaning that thenumber of stars dN with masses between m and m + dm is given by

= αdNdm

A m (1.1)

for Mmin < M < Mmax. The choice α = −2.35 (Salpeter 1955) is so common that it ishas its own standard function call in AMUSE:

mZAMS = new_Salpeter_mass_distribution(N, Mmin, Mmax)

which returns an array of N masses randomly selected between Mmin and Mmax,distributed according to a Salpeter distribution, a power-law distribution withexponent α = −2.35. The resulting mass function is presented in Figure 1.10. Thename mZAMS may seem somewhat arcane: it refers to the mass of a star at themoment of hydrogen ignition (generally called the birth of the star), which is gen-erally referred to as the “zero-age main sequence” (see also Section 3.1).

If you need a power-law mass function with a different slope, you can change theexponent by using a keyword argument, but we recommend that you use the moregeneral version of the mass function generator:

mZAMS = new_powerlaw_mass_distribution(1000,0.1|units.MSun,100|units.MSun,alpha=-2.0)

Astrophysical Recipes

1-24

Page 26: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

which will return a list of 1000 stars with masses between 0.1 and 100 M⊙,distributed according to a power law with α = −2.

The masses can now be easily assigned to the previously generated Plummerdistribution via

bodies.mass = mZAMS

or one can generate a new particle set:

bodies = Particles(mass=mZAMS)

The bodies can subsequently be assigned additional attributes, as already discussed.Note that changing the masses causes the system to have a different total mass and adifferent ratio of potential to kinetic energy, as anticipated in the function used togenerate the positions and velocities, and the system generally needs to be rescaled(see Section 2.3.1).

1.4.5 Stellar Evolution

A star is born—i.e., hydrogen fusion starts—with a certain mass and metallicity, atwhich point we call it a zero-age main sequence star. For a parameterized stellarevolution code (see Section 3.2), the specification stops there—the future evolutionof the star is completely determined via fitting formulae and/or tables.

Figure 1.10. Salpeter mass function for 1000 stars between 1 M⊙ and 100 M⊙, overplotted with an analyticpower law with a slope of −2.35. An example of how this is plotted is presented in Listing 1.4. A script togenerate this figure can be found at ${AMUSE_DIR}/examples/textbook/salpeter.py.

Astrophysical Recipes

1-25

Page 27: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

For a Henyey code (see Section 3.2), these parameters generally also describe thestar, but a number of additional parameters must also be specified. In this type ofcode, the nuclear reaction network, the hydrodynamics, and the radiative transportare generally solved in a number of shells—a star in a Henyey code is layered like anonion. One of the parameters in such a code is the number of layers (onion shells) touse in the code’s description of stellar structure. In general, we must specify the runof temperature, density, etc., throughout the (1D, spherically symmetric) star. TheMESA and EVtwin stellar evolution codes can generate initial stellar models basedon mass and metallicity, but we can also have these codes start from completelyarbitrary structures, under our control. It is possible, for example, to start with a pre-main sequence star, in which case the evolution starts somewhere on the Hayashitrack (see Chapter 3). Another interesting initial stellar model is the hydrogen-exhausted core of a giant without an envelope, which could be interpreted as a zero-age helium main sequence star.

Listing 1.5 presents a simple script to initialize a star of massM and metallicity z,and plots the associated density profile. Figure 1.11 shows the density structure of anM = 2 M⊙ star simulated using the two Henyey codes, EVtwin and MESA. In

import numpyimport mathfrom amuse.units import unitsfrom matplotlib import pyplotfrom prepare_figure import figure_frame, get_distinct

def plot_mass_function(masses, ximf):Mmin = masses.min()Mmax = masses.max()lm = math.log10(0.5*Mmin.value_in(units.MSun))lM = math.log10(1.5*Mmax.value_in(units.MSun))bins = 10**numpy.linspace(lm, lM, 51)Nbin, bin_edges= numpy.histogram(masses.value_in(units.MSun), bins=bins)y = Nbin / (bin_edges[1:] - bin_edges[:-1])x = (bin_edges[1:] + bin_edges[:-1]) / 2.0for i in range(len(y)):

y[i] = max(y[i], 1.e-10)

fig, ax = figure_frame("M$_\odot$", "N", xsize=12, ysize=8)colors = get_distinct(2)pyplot.scatter(x, y, s=100, c=colors[0], lw=0)

c = ((Mmax.value_in(units.MSun)**(ximf+1)) \- (Mmin.value_in(units.MSun)**(ximf+1))) / (ximf+1)

pyplot.plot(x, len(masses)/c * (x**ximf), c=colors[1])pyplot.loglog()

save_file = "salpeter.png"pyplot.savefig(save_file)print "\nSaved figure in file", save_file,"\n"pyplot.show()

Listing 1.4: Routine to plot the generated Salpeter mass function. Code fragment from ${AMUSE_DIR}/examples/textbook/salpeter.py.

Astrophysical Recipes

1-26

Page 28: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

addition, we plot the structure of two 1 M⊙ stars that merge into a single star at avery early stage in their evolution (see Chapter 3 and Listing 3.6 for details). Such acollision would provide a good reason to start with a non-standard stellar initialmodel. In this case, one could use MakeMeAMassiveStar (MMAMS; Lombardiet al. 2002; Gaburov et al. 2008) to generate a stellar initial model, as we will discussin Chapter 3.

def get_density_profile(code=EVtwin, M=2.0|units.MSun, z=0.02):stellar = code()stellar.parameters.metallicity = zstellar.particles.add_particle(Particle(mass=M))radius = stellar.particles[0].get_radius_profile()rho = stellar.particles[0].get_density_profile()stellar.stop()return radius, rho

Listing 1.5: Script to initialize a single zero-age main sequence star using EVTwin. Code fragment from${AMUSE_DIR}/examples/textbook/initialize_single_star.py.

Figure 1.11. Density profile of a star on the zero-age main sequence. All three curves are for a single 2M⊙ star.Two curves are calculated using the stellar structure and evolution codes EVTWIN (blue curve) and MESA (red).The yellow curve is generated from a merger of two 1 M⊙ stars, which are combined conservatively usingMMAMS for constructing a 2 M⊙ in dynamical equilibrium, whose structure is then calculated using MESA. Themerger calculation is performed using the script in Listing 3.6. The script to generate this figure can be found in${AMUSE_DIR}/examples/textbook/merger_stellar_density_profile.py.

Astrophysical Recipes

1-27

Page 29: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

It is interesting that the profiles calculated by the three codes are not the same.The largest differences are in the outer parts of the stars, and these probably do notmake a huge difference to global stellar evolution. However, they may affect quitedramatically how the star appears in a Hertzsprung–Russell diagram, which plotsthe star’s temperature against its luminosity (e.g., Figure 3.10). A larger startranslates to a dimmer and cooler stellar surface.

1.4.6 Hydrodynamical Models

Like particle distributions for gravitational dynamical simulations, hydrodynamicalsimulations also require input density and other distributions. AMUSE providessupport for smoothed particle hydrodynamics (SPH) codes (see Chapter 5), andcontains a variety of distribution-generating functions. Listing 1.6 illustrates theconversion of a one-dimensional stellar evolution model to a three-dimensionalhydrodynamical particle distribution.

In Listing 1.6, in the line

sph_particles = convert_stellar_model_to_SPH(star, Ngas).gas_particles

the parameter gas_particles is returned from the function convert_stellar_model_to_SPH. This is common practice when the called functionreturns a class—in this case, a particle set. In this case, the return value is a classcontaining the particle set core_particle, its radius (core_radius), and agas_particle set. The resulting hydrodynamical models are plotted in Figure1.12 (left panel); Listing 1.7 shows a portion of the plotting code.

We don’t have to start from a stellar model, of course. Listing 1.8 illustrates thecreation of a three-dimensional hydrodynamical particle distribution describing aturbulent molecular cloud. The function molecular_cloud() returns a classwhose parameter result is an SPH particle set:

sph_particles = molecular_cloud(targetN=N, convert_nbody=converter).result

The result is a molecular cloud represented by N equal-mass particles, constructedfrom a homogeneous gas sphere with a turbulent velocity field (Bate et al. 2003).(The system is integrated for a short time after creation to reduce random initial

def stellar_model(N, M, t=0.0|units.Myr):star = Particle(mass=M)stellar_evolution = EVtwin()se_star = stellar_evolution.particles.add_particle(star)print "Evolving", star.mass, "to t=", t.in_(units.Myr)stellar_evolution.evolve_model(t)print "Stellar type:", stellar_evolution.particles.stellar_type.numberprint "Creating SPH particles from the (1D) stellar evolution model"sph_particles = convert_stellar_model_to_SPH(se_star, N).gas_particlesstellar_evolution.stop()return sph_particles

Listing 1.6: Converting an 1D stellar evolution model to a 3D SPH particle representation. Code fragmentfrom ${AMUSE_DIR}/examples/textbook/plot_hydro_density_distributions.py.

Astrophysical Recipes

1-28

Page 30: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

Figure 1.12. Some initial particle distributions for SPH codes. The left panel shows a star of 2 solar masses.The right panel shows a homogeneous spherical distribution with a turbulent velocity field, as is often used insimulations of molecular clouds. Particles are colored by their internal energy (from red for 0.048 km2 s−2 toblue for 1.82 km2 s−2). The script to generate this figure can be found in ${AMUSE_DIR}/examples/textbook/plot_hydro_density_distributions.py.

def plot_ZAMS_stellar_model(N, M):sph_particles = stellar_model(N, M)x_label = "x [R$_\odot$]"y_label = "y [R$_\odot$]"figure, ax = figure_frame(x_label, y_label, xsize=12, ysize=12)sph_particles_plot(sph_particles, min_size = 500,

max_size = 500, alpha=0.01,view=(-2, 2, -2, 2)|units.RSun)

ax.set_facecolor("white")

save_file = "stellar_2MSunZAMS_projected.png"pyplot.savefig(save_file)print "Saved figure in file", save_file, "\n"pyplot.show()

Listing 1.7: Plotting the 3D particle representation using the AMUSE native_plotting module. Codefragment from ${AMUSE_DIR}/examples/textbook/plot_hydro_density_distributions.py.

from amuse.ext.molecular_cloud import molecular_clouddef GMC_model(N, M, R):

converter = nbody_system.nbody_to_si(M, R)sph_particles = molecular_cloud(targetN=N, convert_nbody=converter).resultsph = Fi(converter)sph.gas_particles.add_particle(sph_particles)sph.evolve_model(1|units.day)ch = sph.gas_particles.new_channel_to(sph_particles)ch.copy()sph.stop()return sph_particles

Listing 1.8: Converting a molecular cloud model to a 3D SPH particle representation. Code fragment from${AMUSE_DIR}/examples/textbook/plot_hydro_density_distributions.py.

Astrophysical Recipes

1-29

Page 31: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

noise in the gas distribution.) The resulting density distribution is presented in Figure1.12 (right panel). We will explore such models in more depth in Chapter 5.

We will not dwell on more advanced code coupling strategies here, and similarlydefer discussion of radiative transport to a later chapter. We postpone theseadvanced topics because they require multiple codes to be operational at the sametime. They will be discussed toward the end of this book, in Chapters 6 and 7.

ReferencesAarseth, S. J. 1999, PASP, 111, 1333Aarseth, S. J. 2011, NBODY Codes: Numerical Simulations of Many-body (N-body)

Gravitational Interactions, Astrophysics Source Code Library, ascl:1102.006Backus, J. 1981, History of Programming Languages I (New York: ACM)Bate, M. R., Bonnell, I. A., & Bromm, V. 2003, MNRAS, 339, 577Beck, K., & Andres, C. 2004, Extreme Programming Explained: Embrace Change (2nd ed.;

Reading, MA: Addison-Wesley)Binney, J., & Tremaine, S. 1987, Galactic Dynamics (Princeton, NJ: Princeton Univ. Press)Carroll, L. 1871, Through the Looking-Glass, and What Alice Found There (London: Macmillan)Dorman, F. 2006, in From Queen to Pharaoh, ed C. Roehrig (New York: Metropolitan Museum

of Art)Dorman, P. F. 1991, The Architecture and Decoration of Tombs 71 and 353 (New York:

Metropolitan Museum of Art Egyptian Expedition)Folkner, W. M. 2011, in Journées Systèmes de Référence Spatio-temporels 2010, ed. N. Capitaine

(Pasadena, CA: California Institute of Technology)Fryxell, B., Olson, K., Ricker, P., et al. 2000, ApJS, 131, 273Fryxell, B., Olson, K., Ricker, P., et al. 2010, FLASH: Adaptive Mesh Hydrodynamics Code for

Modeling Astrophysical Thermonuclear Flashes, Astrophysics Source Code Library,ascl:1010.082

Gaburov, E., Lombardi, J. C., & Portegies Zwart, S. 2008, MNRAS, 383, L5Goodwin, S. P., & Whitworth, A. P. 2004, A&A, 413, 929Gosling, J., Joy, B., & Steele, G. L. 1996, The Java Language Specification (1st ed.; Boston, MA:

Addison-Wesley)Gosling, J., Joy, B., Steele, G. L., Bracha, G., & Buckley, A. 2014, The Java Language

Specification, Java SE 8 Edition (1st ed.; Reading, MA: Addison-Wesley)Gropp, W., Ewing, L., Nathan, D., & Anthony, S. 1996, ParC, 22, 789Heggie, D. C., & Mathieu, R. D. 1986, in Springer Lecture Notes in Physics, Vol. 267, The Use of

Supercomputers in Stellar Dynamics, ed. P. Hut, & S. L. W. McMillan (Berlin: Springer)Hénon, M. H. 1971, Ap&SS, 14, 151Holmberg, E. 1941, ApJ, 94, 385Hunter, J. D. 2007, CSE, 9, 90King, I. R. 1966, AJ, 71, 64Lombardi, J. C. Jr., Warren, J. S., Rasio, F. A., et al. 2002, ApJ, 568, 939Maassen, J., & Bal, H. E. 2007, in HPDC ’07: Proc. 16th Int. Symp. on High Performance

Distributed Computing (New York: ACM)Makino, J., & Aarseth, S. J. 1992, PASJ, 44, 141Pelupessy, F. I., van Elteren, A., de Vries, N., et al. 2013, A&A, 557, A84Perez, F., & Granger, B. E. 2007, CSE, 9, 21

Astrophysical Recipes

1-30

Page 32: National Laboratory - IOPscience · change solvers and analyze the results, makes running multiple solvers on the same problem a useful exercise. In this regard, the main advantage

Plummer, H. C. 1911, MNRAS, 71, 460Portegies Zwart, S. 2011, AMUSE: Astrophysical Multipurpose Software Environment,

Astrophysics Source Code Library, ascl:1107.007Portegies Zwart, S., McMillan, S., Harfst, S., et al. 2009, NewA, 14, 369Portegies Zwart, S., McMillan, S. L. W., van Elteren, E., Pelupessy, I., & de Vries, N. 2013,

CoPhC, 183, 456Ritchie, D. M. 1993a, ACM SIGPLAN Not., 28, 201Ritchie, D. M. 1993b, Second ACM SIGPLAN Conf. on History of Programming Languages,

HOPL-II (New York: ACM)Salpeter, E. E. 1955, ApJ, 121, 161Springel, V. 2000, GADGET-2: A Code for Cosmological Simulations of Structure Formation,

Astrophysics Source Code Library, ascl:0003.001Springel, V., Yoshida, N., & White, S. D. M. 2001, NewA, 6, 79Stroustrup, B. 2013, The C++ Programming Language (4th ed.; Reading, MA: Addison-Wesley)van Rossum, G. 1995a, Extending and Embedding the Python Interpreter, Report CS-R9527van Rossum, G. 1995b, Python Library Reference, Report CS-R9524van Rossum, G. 1995c, Python Reference Manual, Report CS-R9525van Rossum, G. 1995d, Python Tutorial, Report CS-R9526Wilkinson, C. K. 1979, Egyptian Wall Paintings. The Metropolitan Museum’s Collection of

Facsimiles (New York: Metropolitan Museum of Art) The Metropolitan Museum of ArtBulletin, Vol. 36, 4

Zemp, M. 2014, Halogen: Multimass spherical structure models for N-body simulations,Astrophysics Source Code Library, ascl:1407.020

Zemp, M., Moore, B., Stadel, J., Carollo, C. M., & Madau, P. 2008, MNRAS, 386, 1543Zuse, K. 1967, ED, 8, 336Zuse, K. 1993, The Computer—My Life (Berlin: Springer)

Astrophysical Recipes

1-31